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_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
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
19 class LazyEncoder(json.JSONEncoder):
20 def default(self, obj):
21 if isinstance(obj, Promise):
22 return force_unicode(obj)
26 def method_decorator(function_decorator):
27 """Converts a function decorator to a method decorator.
29 It just makes it ignore first argument.
31 def decorator(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)
41 def require_login(request):
42 """Return 403 if request is AJAX. Redirect to login page if not."""
44 return HttpResponseForbidden('Not logged in')
46 return HttpResponseRedirect('/uzytkownicy/zaloguj') # next?=request.build_full_path())
49 def placeholdized(form):
50 for field in form.fields.values():
51 field.widget.attrs['placeholder'] = field.label
55 class AjaxableFormView(object):
56 """Subclass this to create an ajaxable view for any form.
58 In the subclass, provide at least form_class.
63 # override to customize form look
64 template = "ajaxable/form.html"
73 full_template = "ajaxable/form_on_page.html"
76 @method_decorator(vary_on_headers('X-Requested-With'))
77 def __call__(self, request, *args, **kwargs):
78 """A view displaying a form, or JSON if request is AJAX."""
79 obj = self.get_object(request, *args, **kwargs)
80 form_args, form_kwargs = self.form_args(request, obj)
82 form_kwargs['prefix'] = self.form_prefix
84 if request.method == "POST":
86 response = verify_honeypot_value(request, None)
90 # do I need to be logged in?
91 if self.POST_login and not request.user.is_authenticated():
92 return require_login(request)
94 form_kwargs['data'] = request.POST
95 form = self.form_class(*form_args, **form_kwargs)
97 add_args = self.success(form, request)
100 'message': self.success_message,
101 'redirect': request.GET.get('next')
104 response_data.update(add_args)
105 if not request.is_ajax() and response_data['redirect']:
106 return HttpResponseRedirect(urlquote_plus(
107 response_data['redirect'], safe='/?=&'))
108 elif request.is_ajax():
109 # Form was sent with errors. Send them back.
112 for key, value in form.errors.items():
113 errors["%s-%s" % (self.form_prefix, key)] = value
116 response_data = {'success': False, 'errors': errors}
119 if request.is_ajax():
120 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
122 if self.POST_login and not request.user.is_authenticated() and not request.is_ajax():
123 return require_login(request)
125 form = self.form_class(*form_args, **form_kwargs)
129 if request.is_ajax():
130 template = self.template
132 template = self.full_template
133 cd = self.context_description(request, obj)
136 if self.placeholdize:
137 form = placeholdized(form)
141 "honeypot": self.honeypot,
142 "placeholdize": self.placeholdize,
143 "submit": self.submit,
144 "action": self.action,
145 "response_data": response_data,
146 "ajax_template": self.template,
148 "view_kwargs": kwargs,
150 context.update(self.extra_context(request, obj))
151 return render_to_response(template, context, context_instance=RequestContext(request))
153 def redirect_or_refresh(self, request, path, message=None):
154 """If the form is AJAX, refresh the page. If not, go to `path`."""
155 if request.is_ajax():
156 output = "<script>window.location.reload()</script>"
158 output = "<div class='normal-text'>" + message + "</div>" + output
159 return HttpResponse(output)
161 return HttpResponseRedirect(path)
163 def get_object(self, request, *args, **kwargs):
164 """Override to parse view args and get some associated data."""
167 def form_args(self, request, obj):
168 """Override to parse view args and give additional args to the form."""
171 def extra_context(self, request, obj):
172 """Override to pass something to template."""
175 def context_description(self, request, obj):
176 """Description to appear in standalone form, but not in AJAX form."""
179 def success(self, form, request):
180 """What to do when the form is valid.
182 By default, just save the form.
185 return form.save(request)