Version 7 (modified by 18 years ago) ( diff ) | ,
---|
Introduction
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.
The server view
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. ...
The client view
Now that the server view is writtent, we could try next to arrange the client code to fit into one, unportable template chunk, however it's usually best to split the work in smaller pieces, at least for being nice to the maintainers (You). :-)
So let's move on in writing our own Dojo template, where we will make an abstraction of all our applied Dojo concepts.
Quite frankly, that part is going straight-forward, as we're only writing HTML:
<script type="text/javascript"> djConfig = { isDebug:true, debugAtAllCosts:false }; </script> <script type="text/javascript" src="/media/js/dojo/dojo.js"></script> <script type="text/javascript"> dojo.require("dojo.event.*"); // sophisticated AOP event handling dojo.require("dojo.io.*"); // for Ajax requests dojo.require("dojo.json"); // serialization to JSON </script> <script type="text/javascript" src="/media/js/ajax.js"></script>
The djConfig.isDebug parameter is important for debugging, so you should consider setting it to "true" when inspecting you're application with Firebug or something else.
Optionally, you can "bake" your own Dojo file, and substract the baked modules from the list of required modules above, so we wont load the already compiled Dojo modules twice. Let's push forward and write down the core JS file, for doing AJAX-related things with our own custom-compiled Dojo module:
[ajax-related things here...]
Attachments (2)
-
ajax.js
(2.1 KB
) - added by 18 years ago.
script for handling form validation errors w/ dojo
-
ajax.2.js
(2.1 KB
) - added by 18 years ago.
script for handling form validation errors w/ dojo
Download all attachments as: .zip