1 from functools import wraps
3 from django.http import (HttpResponse, HttpResponseRedirect,
5 from django.shortcuts import render_to_response
6 from django.template import RequestContext
7 from django.utils.cache import patch_vary_headers
8 from django.utils.encoding import force_unicode
9 from django.utils.functional import Promise
10 from django.utils.http import urlquote_plus
11 from django.utils import simplejson
12 from django.utils.translation import ugettext_lazy as _
13 from django.views.decorators.vary import vary_on_headers
16 class LazyEncoder(simplejson.JSONEncoder):
17 def default(self, obj):
18 if isinstance(obj, Promise):
19 return force_unicode(obj)
22 # shortcut for JSON reponses
23 class JSONResponse(HttpResponse):
24 def __init__(self, data={}, callback=None, **kwargs):
26 kwargs.pop('mimetype', None)
27 data = simplejson.dumps(data)
29 data = callback + "(" + data + ");"
30 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
33 def method_decorator(function_decorator):
34 """Converts a function decorator to a method decorator.
36 It just makes it ignore first argument.
38 def decorator(method):
40 def wrapped_method(self, *args, **kwargs):
41 def function(*fargs, **fkwargs):
42 return method(self, *fargs, **fkwargs)
43 return function_decorator(function)(*args, **kwargs)
48 def require_login(request):
49 """Return 403 if request is AJAX. Redirect to login page if not."""
51 return HttpResponseForbidden('Not logged in')
53 return HttpResponseRedirect('/uzytkownicy/zaloguj')# next?=request.build_full_path())
56 class AjaxableFormView(object):
57 """Subclass this to create an ajaxable view for any form.
59 In the subclass, provide at least form_class.
63 # override to customize form look
64 template = "ajaxable/form.html"
72 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 form_args, form_kwargs = self.form_args(request, *args, **kwargs)
79 form_kwargs['prefix'] = self.form_prefix
81 if request.method == "POST":
82 # do I need to be logged in?
83 if self.POST_login and not request.user.is_authenticated():
84 return require_login(request)
86 form_kwargs['data'] = request.POST
87 form = self.form_class(*form_args, **form_kwargs)
89 add_args = self.success(form, request)
90 redirect = request.GET.get('next')
91 if not request.is_ajax() and redirect:
92 return HttpResponseRedirect(urlquote_plus(
93 redirect, safe='/?=&'))
94 response_data = {'success': True,
95 'message': self.success_message, 'redirect': redirect}
97 response_data.update(add_args)
98 elif request.is_ajax():
99 # Form was sent with errors. Send them back.
102 for key, value in form.errors.items():
103 errors["%s-%s" % (self.form_prefix, key)] = value
106 response_data = {'success': False, 'errors': errors}
107 if request.is_ajax():
108 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
110 if (self.POST_login and not request.user.is_authenticated()
111 and not request.is_ajax()):
112 return require_login(request)
114 form = self.form_class(*form_args, **form_kwargs)
117 template = self.template if request.is_ajax() else self.full_template
121 "submit": self.submit,
122 "response_data": response_data,
123 "ajax_template": self.template,
125 "view_kwargs": kwargs,
127 context.update(self.extra_context())
128 return render_to_response(template, context,
129 context_instance=RequestContext(request))
131 def form_args(self, request, *args, **kwargs):
132 """Override to parse view args and give additional args to the form."""
135 def extra_context(self):
136 """Override to pass something to template."""
139 def success(self, form, request):
140 """What to do when the form is valid.
142 By default, just save the form.
145 return form.save(request)