ajax_validator generic view

 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
from django.utils import simplejson
from django.http import HttpResponse
from django.core.urlresolvers import get_mod_func

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

# ajax_validator  # {{{
def ajax_validator(request, form_cls):
    mod_name, form_name = get_mod_func(form_cls)
    form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    form = form_cls(request.POST)
    if "field" in request.GET: 
        errors = form.errors.get(request.GET["field"])
        if errors: errors = errors.as_text()
    else:
        errors = form.errors
    return JSONResponse(
        { "errors": errors, "valid": not errors }
    ) 
# }}}

# Usage: in urls.py have something like this:
urlpatterns = patterns('',
    # ... other patterns
    (
        r'^ajax/validate-registration-form/$', 'ajax_validator',
        { 'form_cls': 'myproject.accounts.forms.RegistrationForm' }
    ),
)

More like this

  1. Jquery ajax csrf framework for Django by chriszweber 1 year, 4 months ago
  2. Ajax form with jQuery by Donn 4 years, 9 months ago
  3. use oldforms validators in newforms forms by garywilson 6 years, 1 month ago
  4. AjaxForm Base Classes by btaylordesign 2 years, 2 months ago
  5. ajax form handler generic view by amitu 4 years, 7 months ago

Comments

amitu (on October 14, 2008):

As a friend said somewhere, this can be made even more generic by making form_cls optional, and passing it from ajax, though it may have some security implications.

#

robertrv (on October 16, 2008):

maybe you can have a look to this (http://code.google.com/p/django-ajax-validation/) and even make any contribution

#

amitu (on October 29, 2009):

This is now maintained as a part of dutils.

#

(Forgotten your password?)