Login

django ajax_view decorator

Author:
chizcracker
Posted:
May 22, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

All credit goes to Peter Coles.

http://mrcoles.com/blog/decorator-django-ajax-views/#c281

I slightly modified the original code to work without passing parameters to decorator.

I will delete this post if anyone does not want this snippet to be posted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseForbidden, HttpResponseBadRequest
from django.utils.safestring import mark_safe
from django.utils.decorators import available_attrs
from django.utils import simplejson
from functools import wraps

_ERROR_MSG = '<!DOCTYPE html><html lang="en"><body><h1>%s</h1><p>%%s</p></body></html>'
_400_ERROR = _ERROR_MSG % '400 Bad Request'
_403_ERROR = _ERROR_MSG % '403 Forbidden'
_405_ERROR = _ERROR_MSG % '405 Not Allowed'


"""
usage:
    @ajax_view
    def foo():

or 
    @ajax_view(option)
    def foo():
"""


def ajax_view(function=None, FormClass=None, method="GET", login_required=True, ajax_required=True, json_form_errors=False):    
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _ajax_view(request, *args, **kwargs):
            if request.method != method and method != 'REQUEST':
                return HttpResponseNotAllowed(mark_safe(_405_ERROR % ("Request must be a %s." % method)))
            if ajax_required and not request.is_ajax():
                return HttpResponseForbidden(mark_safe(_403_ERROR % "Request must be set via AJAX."))
            if login_required and not request.user.is_authenticated():
                return HttpResponseForbidden(mark_safe(_403_ERROR % "Login required"))

            if FormClass:
                f = FormClass(getattr(request, method))
                    
                if not f.is_valid():
                    if json_form_errors:
                        errors = dict((k, [unicode(x) for x in v]) for k,v in f.errors.items())
                        return HttpResponse(simplejson.dumps({'error': 'form', 'errors': errors}), 'application/json')
                    else:   
                        return HttpResponseBadRequest(mark_safe(_400_ERROR % ('Invalid form<br />' + f.errors.as_ul())))
                request.form = f
            return view_func(request, *args, **kwargs)
        return _ajax_view
            
    if function:
        return decorator(function)
    return decorator

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.