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' }
),
)
Comments
As a friend said somewhere, this can be made even more generic by making
form_clsoptional, and passing it from ajax, though it may have some security implications.#
maybe you can have a look to this (http://code.google.com/p/django-ajax-validation/) and even make any contribution
#
This is now maintained as a part of dutils.
#