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' } ), )