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
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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.