Fix section counting/targetting from search snippet
[wolnelektury.git] / apps / ajaxable / utils.py
1 from functools import wraps
2
3 from django.http import (HttpResponse, HttpResponseRedirect,
4         HttpResponseForbidden)
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
14
15
16 class LazyEncoder(simplejson.JSONEncoder):
17     def default(self, obj):
18         if isinstance(obj, Promise):
19             return force_unicode(obj)
20         return obj
21
22 # shortcut for JSON reponses
23 class JSONResponse(HttpResponse):
24     def __init__(self, data={}, callback=None, **kwargs):
25         # get rid of mimetype
26         kwargs.pop('mimetype', None)
27         data = simplejson.dumps(data)
28         if callback:
29             data = callback + "(" + data + ");" 
30         super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
31
32
33 def method_decorator(function_decorator):
34     """Converts a function decorator to a method decorator.
35
36     It just makes it ignore first argument.
37     """
38     def decorator(method):
39         @wraps(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)
44         return wrapped_method
45     return decorator
46
47
48 def require_login(request):
49     """Return 403 if request is AJAX. Redirect to login page if not."""
50     if request.is_ajax():
51         return HttpResponseForbidden('Not logged in')
52     else:
53         return HttpResponseRedirect('/uzytkownicy/zaloguj')# next?=request.build_full_path())
54
55
56 def placeholdized(form):
57     for field in form.fields.values():
58         field.widget.attrs['placeholder'] = field.label
59     return form
60
61
62 class AjaxableFormView(object):
63     """Subclass this to create an ajaxable view for any form.
64
65     In the subclass, provide at least form_class.
66
67     """
68     form_class = None
69     placeholdize = False
70     # override to customize form look
71     template = "ajaxable/form.html"
72     submit = _('Send')
73     
74     title = ''
75     success_message = ''
76     POST_login = False
77     formname = "form"
78     form_prefix = None
79     full_template = "ajaxable/form_on_page.html"
80
81     @method_decorator(vary_on_headers('X-Requested-With'))
82     def __call__(self, request, *args, **kwargs):
83         """A view displaying a form, or JSON if request is AJAX."""
84         #form_class = placeholdized(self.form_class) if self.placeholdize else self.form_class
85         form_args, form_kwargs = self.form_args(request, *args, **kwargs)
86         if self.form_prefix:
87             form_kwargs['prefix'] = self.form_prefix
88
89         if request.method == "POST":
90             # do I need to be logged in?
91             if self.POST_login and not request.user.is_authenticated():
92                 return require_login(request)
93
94             form_kwargs['data'] = request.POST
95             form = self.form_class(*form_args, **form_kwargs)
96             if form.is_valid():
97                 add_args = self.success(form, request)
98                 redirect = request.GET.get('next')
99                 if not request.is_ajax() and redirect:
100                     return HttpResponseRedirect(urlquote_plus(
101                             redirect, safe='/?=&'))
102                 response_data = {'success': True, 
103                     'message': self.success_message, 'redirect': redirect}
104                 if add_args:
105                     response_data.update(add_args)
106             elif request.is_ajax():
107                 # Form was sent with errors. Send them back.
108                 if self.form_prefix:
109                     errors = {}
110                     for key, value in form.errors.items():
111                         errors["%s-%s" % (self.form_prefix, key)] = value
112                 else:
113                     errors = form.errors
114                 response_data = {'success': False, 'errors': errors}
115             else:
116                 response_data = None
117             if request.is_ajax():
118                 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
119         else:
120             if (self.POST_login and not request.user.is_authenticated()
121                     and not request.is_ajax()):
122                 return require_login(request)
123
124             form = self.form_class(*form_args, **form_kwargs)
125             response_data = None
126
127         template = self.template if request.is_ajax() else self.full_template
128         if self.placeholdize:
129             form = placeholdized(form)
130         context = {
131                 self.formname: form, 
132                 "title": self.title,
133                 "placeholdize": self.placeholdize,
134                 "submit": self.submit,
135                 "response_data": response_data,
136                 "ajax_template": self.template,
137                 "view_args": args,
138                 "view_kwargs": kwargs,
139             }
140         context.update(self.extra_context())
141         return render_to_response(template, context,
142             context_instance=RequestContext(request))
143
144     def form_args(self, request, *args, **kwargs):
145         """Override to parse view args and give additional args to the form."""
146         return (), {}
147
148     def extra_context(self):
149         """Override to pass something to template."""
150         return {}
151
152     def success(self, form, request):
153         """What to do when the form is valid.
154         
155         By default, just save the form.
156
157         """
158         return form.save(request)