1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from functools import wraps
6 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
7 from django.shortcuts import render
8 from django.utils.encoding import force_text
9 from django.utils.functional import Promise
10 from django.utils.http import urlquote_plus
12 from django.utils.translation import ugettext_lazy as _
13 from django.views.decorators.vary import vary_on_headers
14 from honeypot.decorators import verify_honeypot_value
17 class LazyEncoder(json.JSONEncoder):
18 def default(self, obj):
19 if isinstance(obj, Promise):
20 return force_text(obj)
24 def method_decorator(function_decorator):
25 """Converts a function decorator to a method decorator.
27 It just makes it ignore first argument.
29 def decorator(method):
31 def wrapped_method(self, *args, **kwargs):
32 def function(*fargs, **fkwargs):
33 return method(self, *fargs, **fkwargs)
34 return function_decorator(function)(*args, **kwargs)
39 def require_login(request):
40 """Return 403 if request is AJAX. Redirect to login page if not."""
42 return HttpResponseForbidden('Not logged in')
44 return HttpResponseRedirect('/uzytkownicy/zaloguj') # next?=request.build_full_path())
47 def placeholdized(form):
48 for field in form.fields.values():
49 field.widget.attrs['placeholder'] = field.label + ('*' if field.required else '')
53 class AjaxableFormView(object):
54 """Subclass this to create an ajaxable view for any form.
56 In the subclass, provide at least form_class.
61 # override to customize form look
62 template = "ajaxable/form.html"
71 full_template = "ajaxable/form_on_page.html"
74 @method_decorator(vary_on_headers('X-Requested-With'))
75 def __call__(self, request, *args, **kwargs):
76 """A view displaying a form, or JSON if request is AJAX."""
77 obj = self.get_object(request, *args, **kwargs)
79 response = self.validate_object(obj, request)
83 form_args, form_kwargs = self.form_args(request, obj)
85 form_kwargs['prefix'] = self.form_prefix
87 if request.method == "POST":
89 response = verify_honeypot_value(request, None)
93 # do I need to be logged in?
94 if self.POST_login and not request.user.is_authenticated:
95 return require_login(request)
97 form_kwargs['data'] = request.POST
98 form = self.form_class(*form_args, **form_kwargs)
100 add_args = self.success(form, request)
103 'message': self.success_message,
104 'redirect': request.GET.get('next')
107 response_data.update(add_args)
108 if not request.is_ajax() and response_data['redirect']:
109 return HttpResponseRedirect(urlquote_plus(
110 response_data['redirect'], safe='/?=&'))
111 elif request.is_ajax():
112 # Form was sent with errors. Send them back.
115 for key, value in form.errors.items():
116 errors["%s-%s" % (self.form_prefix, key)] = value
119 response_data = {'success': False, 'errors': errors}
122 if request.is_ajax():
123 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
125 if self.POST_login and not request.user.is_authenticated and not request.is_ajax():
126 return require_login(request)
128 form = self.form_class(*form_args, **form_kwargs)
132 if request.is_ajax():
133 template = self.template
135 template = self.full_template
136 cd = self.context_description(request, obj)
139 if self.placeholdize:
140 form = placeholdized(form)
144 "honeypot": self.honeypot,
145 "placeholdize": self.placeholdize,
146 "submit": self.submit,
147 "action": self.action,
148 "response_data": response_data,
149 "ajax_template": self.template,
151 "view_kwargs": kwargs,
153 context.update(self.extra_context(request, obj))
154 return render(request, template, context)
156 def validate_object(self, obj, request):
159 def redirect_or_refresh(self, request, path, message=None):
160 """If the form is AJAX, refresh the page. If not, go to `path`."""
161 if request.is_ajax():
162 output = "<script>window.location.reload()</script>"
164 output = "<div class='normal-text'>" + message + "</div>" + output
165 return HttpResponse(output)
167 return HttpResponseRedirect(path)
169 def get_object(self, request, *args, **kwargs):
170 """Override to parse view args and get some associated data."""
173 def form_args(self, request, obj):
174 """Override to parse view args and give additional args to the form."""
177 def extra_context(self, request, obj):
178 """Override to pass something to template."""
181 def context_description(self, request, obj):
182 """Description to appear in standalone form, but not in AJAX form."""
185 def success(self, form, request):
186 """What to do when the form is valid.
188 By default, just save the form.
191 return form.save(request)