Login

ajax_validator generic view

Author:
amitu
Posted:
October 14, 2008
Language:
Python
Version:
1.0
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. 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

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.