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.
5 from functools import wraps
7 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
8 from django.shortcuts import render
9 from django.utils.encoding import force_unicode
10 from django.utils.functional import Promise
11 from django.utils.http import urlquote_plus
13 from django.utils.translation import ugettext_lazy as _
14 from django.views.decorators.vary import vary_on_headers
15 from honeypot.decorators import verify_honeypot_value
18 class LazyEncoder(json.JSONEncoder):
19 def default(self, obj):
20 if isinstance(obj, Promise):
21 return force_unicode(obj)
25 def method_decorator(function_decorator):
26 """Converts a function decorator to a method decorator.
28 It just makes it ignore first argument.
30 def decorator(method):
32 def wrapped_method(self, *args, **kwargs):
33 def function(*fargs, **fkwargs):
34 return method(self, *fargs, **fkwargs)
35 return function_decorator(function)(*args, **kwargs)
40 def require_login(request):
41 """Return 403 if request is AJAX. Redirect to login page if not."""
43 return HttpResponseForbidden('Not logged in')
45 return HttpResponseRedirect('/uzytkownicy/zaloguj') # next?=request.build_full_path())
48 def placeholdized(form):
49 for field in form.fields.values():
50 field.widget.attrs['placeholder'] = field.label + ('*' if field.required else '')
54 class AjaxableFormView(object):
55 """Subclass this to create an ajaxable view for any form.
57 In the subclass, provide at least form_class.
62 # override to customize form look
63 template = "ajaxable/form.html"
72 full_template = "ajaxable/form_on_page.html"
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)
80 response = self.validate_object(obj, request)
84 form_args, form_kwargs = self.form_args(request, obj)
86 form_kwargs['prefix'] = self.form_prefix
88 if request.method == "POST":
90 response = verify_honeypot_value(request, None)
94 # do I need to be logged in?
95 if self.POST_login and not request.user.is_authenticated():
96 return require_login(request)
98 form_kwargs['data'] = request.POST
99 form = self.form_class(*form_args, **form_kwargs)
101 add_args = self.success(form, request)
104 'message': self.success_message,
105 'redirect': request.GET.get('next')
108 response_data.update(add_args)
109 if not request.is_ajax() and response_data['redirect']:
110 return HttpResponseRedirect(urlquote_plus(
111 response_data['redirect'], safe='/?=&'))
112 elif request.is_ajax():
113 # Form was sent with errors. Send them back.
116 for key, value in form.errors.items():
117 errors["%s-%s" % (self.form_prefix, key)] = value
120 response_data = {'success': False, 'errors': errors}
123 if request.is_ajax():
124 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
126 if self.POST_login and not request.user.is_authenticated() and not request.is_ajax():
127 return require_login(request)
129 form = self.form_class(*form_args, **form_kwargs)
133 if request.is_ajax():
134 template = self.template
136 template = self.full_template
137 cd = self.context_description(request, obj)
140 if self.placeholdize:
141 form = placeholdized(form)
145 "honeypot": self.honeypot,
146 "placeholdize": self.placeholdize,
147 "submit": self.submit,
148 "action": self.action,
149 "response_data": response_data,
150 "ajax_template": self.template,
152 "view_kwargs": kwargs,
154 context.update(self.extra_context(request, obj))
155 return render(request, template, context)
157 def validate_object(self, obj, request):
160 def redirect_or_refresh(self, request, path, message=None):
161 """If the form is AJAX, refresh the page. If not, go to `path`."""
162 if request.is_ajax():
163 output = "<script>window.location.reload()</script>"
165 output = "<div class='normal-text'>" + message + "</div>" + output
166 return HttpResponse(output)
168 return HttpResponseRedirect(path)
170 def get_object(self, request, *args, **kwargs):
171 """Override to parse view args and get some associated data."""
174 def form_args(self, request, obj):
175 """Override to parse view args and give additional args to the form."""
178 def extra_context(self, request, obj):
179 """Override to pass something to template."""
182 def context_description(self, request, obj):
183 """Description to appear in standalone form, but not in AJAX form."""
186 def success(self, form, request):
187 """What to do when the form is valid.
189 By default, just save the form.
192 return form.save(request)