Version 4 (modified by erob@…, 18 years ago) ( diff )

added register view (initial rev)

Here's a simple recipe that worked for me. It is quite inspired by the AjaxDojoFormSub example―and from this tutorial―except that this recipe is expected to use python-cjson for receiving JSON data.

My initial objective was to display validation errors without doing a page-refresh, by using JSON for carrying errors (or whatever else you could possibly imagine) back to the client browser.

First thing first, lets write the server view, as its really important to make the forms working without the use of Javascript:

import cjson
from django.http import HttpResponse
from django.template import loader, Context

def register(request):
    # Register or reports any (new)form-validation errors using JSON.
    form = ExampleForm(request.POST)
    t = loader.get_template('myform.html')
    if not form.is_valid():
       # Return JSON object containing the errors object.
       if xhr:
          return HttpResponse(cjson.encode(form.errors), mimetype='text/javascript')
       else:
          # vanilla Http response fallback
          return HttpResponse(t.render(Context({'errors' : form.errors }))
    else:
       # Do something when the form has been validated.
       ...    

Then, we should definitely try to explain the client side:

[...]

Attachments (2)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.
Back to Top