Login

ajax_validator generic view

Author:
amitu
Posted:
October 14, 2008
Language:
Python
Version:
1.0
Tags:
ajax javascript view generic jquery validation form
Score:
3 (after 3 ratings)

Sample jQuery javascript to use this view:

$(function(){
    $("#id_username, #id_password, #id_password2, #id_email").blur(function(){
        var url = "/ajax/validate-registration-form/?field=" + this.name;
        var field = this.name;
        $.ajax({
            url: url, data: $("#registration_form").serialize(),
            type: "post", dataType: "json",    
            success: function (response){ 
                if(response.valid)
                {
                    $("#"+field+"_errors").html("Sounds good");
                }
                else
                {
                    $("#"+field+"_errors").html(response.errors);
                }
            }
        });
    });
});

For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.

 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. Ajax form with jQuery by Donn 7 years ago
  2. AjaxForm Base Classes by btaylordesign 4 years, 5 months ago
  3. Jquery ajax csrf framework for Django by chriszweber 3 years, 7 months ago
  4. Dynamically add inlines by MasonM 6 years, 2 months ago
  5. Adding buttons to submit line in a Admin page by marinho 7 years, 3 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.

#

Please login first before commenting.