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 urllib.parse import quote_plus
8 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
9 from django.shortcuts import render
10 from django.utils.encoding import force_str
11 from django.utils.functional import Promise
12 from django.utils.translation import gettext_lazy as _
13 from django.views.decorators.vary import vary_on_headers
14 from honeypot.decorators import verify_honeypot_value
15 from wolnelektury.utils import is_ajax
18 class LazyEncoder(json.JSONEncoder):
20 if isinstance(o, Promise):
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')
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:
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 is_ajax(request) and response_data['redirect']:
109 return HttpResponseRedirect(quote_plus(
110 response_data['redirect'], safe='/?=&'))
111 elif is_ajax(request):
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}
123 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
125 if self.POST_login and not request.user.is_authenticated and not is_ajax(request):
126 return require_login(request)
128 form = self.form_class(*form_args, **form_kwargs)
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`."""
162 output = "<script>window.location.reload()</script>"
164 output = "<div class='normal-text'>" + message + "</div>" + output
165 return HttpResponse(output)
166 return HttpResponseRedirect(path)
168 def get_object(self, request, *args, **kwargs):
169 """Override to parse view args and get some associated data."""
172 def form_args(self, request, obj):
173 """Override to parse view args and give additional args to the form."""
176 def extra_context(self, request, obj):
177 """Override to pass something to template."""
180 def context_description(self, request, obj):
181 """Description to appear in standalone form, but not in AJAX form."""
184 def success(self, form, request):
185 """What to do when the form is valid.
187 By default, just save the form.
190 return form.save(request)