Login

ajax form handler generic view

Author:
amitu
Posted:
October 26, 2008
Language:
Python
Version:
1.0
Tags:
ajax form generic-view
Score:
7 (after 7 ratings)

Some ajax heavy apps require a lot of views that are merely a wrapper around the form. This generic view can be used for them.

 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
# imports # {{{
from django.utils import simplejson
from django.http import HttpResponse, Http404
from django.utils.functional import Promise
from django.utils.translation import force_unicode
from django.utils.simplejson import JSONEncoder
from django.conf import settings
# }}}

# JSONResponse # {{{
class LazyEncoder(simplejson.JSONEncoder):
    def default(self, o):
        if isinstance(o, Promise):
            return force_unicode(o)
        else:
            return super(LazyEncoder, self).default(o)

class JSONResponse(HttpResponse):
    def __init__(self, data):
        HttpResponse.__init__(
            self, content=simplejson.dumps(data, cls=LazyEncoder),
            #mimetype="text/html",
        ) 
# }}}

# ajax_form_handler # {{{
def ajax_form_handler(
    request, form_cls, require_login=True, allow_get=settings.DEBUG
):
    if require_login and not request.user.is_authenticated(): 
        raise Http404("login required")
    if not allow_get and request.method != "POST":
        raise Http404("only post allowed")
    if isinstance(form_cls, basestring):
        # can take form_cls of the form: "project.app.forms.FormName"
        from django.core.urlresolvers import get_mod_func
        mod_name, form_name = get_mod_func(form_cls)
        form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    form = form_cls(request, request.REQUEST)
    if form.is_valid():
        return JSONResponse({ 'success': True, 'response': form.save() })
    return JSONResponse({ 'success': False, 'errors': form.errors })
# }}}

More like this

  1. ajax_validator generic view by amitu 6 years, 10 months ago
  2. Login via ExtJS by davidblewett 7 years, 2 months ago
  3. Ajax auto-filtered Foreign Key Field by anentropic 5 years, 9 months ago
  4. login_required for a generic view in URLconf by pgugged 7 years, 1 month ago
  5. save form in ajax with jquery in django by ralphleyga 5 years ago

Comments

Scanner (on October 27, 2008):

Hm. Instead of passing in a boolean 'require_login' I modified snippet to see if require_login was a callable. This lets me pass such things as a lambda that requires a certain permission instead of just requiring a login (and a slight change in the 404 text to 'permission denied')

#

Please login first before commenting.