Blogger Template by Blogcrowds.


Simple way to implement Ajax in Django with the help of Dojo toolkit.

  • Create a model for Book

class Book(models.Model):
name = models.CharField(max_length = 50)
author = models.CharField(max_length = 60)
year = models.IntegerField()
ref_no =models.IntegerField()

  • Create a ModelForm for 'Book' Models

  • Write a function for save the details of 'Book'

  • class BookForm(ModelForm):
        class Meta:
    def AddBook(request):
        if request.method == 'POST':
            if form.is_valid():
       save Book
                return HttpResponse ("1")#if Book object stored, return confirmation.
                return HttpResponse ("Please check the form data.")# if form validation failed
            return render_to_response("Register.html",{'Form':form})

    3. Register.html

    • Import Dojo necessary packages to your html file

    • Import Ajax.js where we are going to write the ajax function.

    • Div 'result' for show the response(from after the form submission.

    <script type="text/javascript" src="/path_to_dojo/dojo-release-1.2.0/dojo/dojo.js" djConfig="parseOnLoad:true"></script>
    <script type="text/javascript" src="ajax.js" ></script>
    <div id=”result”></div>
    <div id=”FormDiv”>
    <form id="AddBook">
    <input type="submit" onclick="return ValidateBook();">


    • Write a function named as ValidateBook

    • Declare a variable 'kw'

    • Variable 'data' contains the response .

    • If the Book details storeded in database, then will return '1' for confirmation

    • If Book details failed to validate , then error response will return.

    function ValidateBook()
    var kw = {
    form: dojo.byId("AddBook"),
    url: "/book/add/",
    load: function(data){
    if (data==1)
    dojo.byId("result").innerHTML="Book details has been registered successfully. ;

    dojo.byId("test").innerHTML = data;
    error: function(data){
    console.debug("An error occurred: ", data);
    timeout: 5000,
    form: "AddBook"
    dojo.xhrPost(kw); //Servlet get argement with doPost


Post a Comment

Newer Post Older Post Home