#12 wystawione 20 najpopularniejszych książek
[wolnelektury.git] / src / ajaxable / utils.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from functools import wraps
6
7 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
8 from django.shortcuts import render_to_response
9 from django.template import RequestContext
10 from django.utils.encoding import force_unicode
11 from django.utils.functional import Promise
12 from django.utils.http import urlquote_plus
13 import json
14 from django.utils.translation import ugettext_lazy as _
15 from django.views.decorators.vary import vary_on_headers
16 from honeypot.decorators import verify_honeypot_value
17
18
19 class LazyEncoder(json.JSONEncoder):
20     def default(self, obj):
21         if isinstance(obj, Promise):
22             return force_unicode(obj)
23         return obj
24
25
26 def method_decorator(function_decorator):
27     """Converts a function decorator to a method decorator.
28
29     It just makes it ignore first argument.
30     """
31     def decorator(method):
32         @wraps(method)
33         def wrapped_method(self, *args, **kwargs):
34             def function(*fargs, **fkwargs):
35                 return method(self, *fargs, **fkwargs)
36             return function_decorator(function)(*args, **kwargs)
37         return wrapped_method
38     return decorator
39
40
41 def require_login(request):
42     """Return 403 if request is AJAX. Redirect to login page if not."""
43     if request.is_ajax():
44         return HttpResponseForbidden('Not logged in')
45     else:
46         return HttpResponseRedirect('/uzytkownicy/zaloguj')  # next?=request.build_full_path())
47
48
49 def placeholdized(form):
50     for field in form.fields.values():
51         field.widget.attrs['placeholder'] = field.label
52     return form
53
54
55 class AjaxableFormView(object):
56     """Subclass this to create an ajaxable view for any form.
57
58     In the subclass, provide at least form_class.
59
60     """
61     form_class = None
62     placeholdize = False
63     # override to customize form look
64     template = "ajaxable/form.html"
65     submit = _('Send')
66
67     title = ''
68     success_message = ''
69     POST_login = False
70     formname = "form"
71     form_prefix = None
72     full_template = "ajaxable/form_on_page.html"
73     honeypot = False
74
75     @method_decorator(vary_on_headers('X-Requested-With'))
76     def __call__(self, request, *args, **kwargs):
77         """A view displaying a form, or JSON if request is AJAX."""
78         obj = self.get_object(request, *args, **kwargs)
79         form_args, form_kwargs = self.form_args(request, obj)
80         if self.form_prefix:
81             form_kwargs['prefix'] = self.form_prefix
82
83         if request.method == "POST":
84             if self.honeypot:
85                 response = verify_honeypot_value(request, None)
86                 if response:
87                     return response
88
89             # do I need to be logged in?
90             if self.POST_login and not request.user.is_authenticated():
91                 return require_login(request)
92
93             form_kwargs['data'] = request.POST
94             form = self.form_class(*form_args, **form_kwargs)
95             if form.is_valid():
96                 add_args = self.success(form, request)
97                 response_data = {
98                     'success': True,
99                     'message': self.success_message,
100                     'redirect': request.GET.get('next')
101                     }
102                 if add_args:
103                     response_data.update(add_args)
104                 if not request.is_ajax() and response_data['redirect']:
105                     return HttpResponseRedirect(urlquote_plus(
106                             response_data['redirect'], safe='/?=&'))
107             elif request.is_ajax():
108                 # Form was sent with errors. Send them back.
109                 if self.form_prefix:
110                     errors = {}
111                     for key, value in form.errors.items():
112                         errors["%s-%s" % (self.form_prefix, key)] = value
113                 else:
114                     errors = form.errors
115                 response_data = {'success': False, 'errors': errors}
116             else:
117                 response_data = None
118             if request.is_ajax():
119                 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
120         else:
121             if self.POST_login and not request.user.is_authenticated() and not request.is_ajax():
122                 return require_login(request)
123
124             form = self.form_class(*form_args, **form_kwargs)
125             response_data = None
126
127         title = self.title
128         if request.is_ajax():
129             template = self.template
130         else:
131             template = self.full_template
132             cd = self.context_description(request, obj)
133             if cd:
134                 title += ": " + cd
135         if self.placeholdize:
136             form = placeholdized(form)
137         context = {
138                 self.formname: form,
139                 "title": title,
140                 "honeypot": self.honeypot,
141                 "placeholdize": self.placeholdize,
142                 "submit": self.submit,
143                 "response_data": response_data,
144                 "ajax_template": self.template,
145                 "view_args": args,
146                 "view_kwargs": kwargs,
147             }
148         context.update(self.extra_context(request, obj))
149         return render_to_response(template, context, context_instance=RequestContext(request))
150
151     def redirect_or_refresh(self, request, path, message=None):
152         """If the form is AJAX, refresh the page. If not, go to `path`."""
153         if request.is_ajax():
154             output = "<script>window.location.reload()</script>"
155             if message:
156                 output = "<div class='normal-text'>" + message + "</div>" + output
157             return HttpResponse(output)
158         else:
159             return HttpResponseRedirect(path)
160
161     def get_object(self, request, *args, **kwargs):
162         """Override to parse view args and get some associated data."""
163         return None
164
165     def form_args(self, request, obj):
166         """Override to parse view args and give additional args to the form."""
167         return (), {}
168
169     def extra_context(self, request, obj):
170         """Override to pass something to template."""
171         return {}
172
173     def context_description(self, request, obj):
174         """Description to appear in standalone form, but not in AJAX form."""
175         return ""
176
177     def success(self, form, request):
178         """What to do when the form is valid.
179
180         By default, just save the form.
181
182         """
183         return form.save(request)