Introduction:
Simple way to implement Ajax in Django with the help of Dojo toolkit.
1.Models.py
Create a model for Book
class Book(models.Model):
author = models.CharField(max_length = 60)
year = models.IntegerField()
ref_no =models.IntegerField()
2.Form.py
Create a ModelForm for 'Book' Models
Write a function for save the details of 'Book'
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 form.py) after the form submission.
Write a function named as ValidateBook
Declare a variable 'kw'
Variable 'data' contains the response .
If the Book details storeded in database, then form.py will return '1' for confirmation
If Book details failed to validate , then error response will return.
class BookForm(ModelForm):
class Meta:
model=Book
def AddBook(request):
if request.method == 'POST':
form=BookForm(request.POST)
if form.is_valid():
form.save()# save Book
return HttpResponse ("1")#if Book object stored, return confirmation.
else:
return HttpResponse ("Please check the form data.")# if form validation failed
else:
form=BookForm()
return render_to_response("Register.html",{'Form':form})
3. Register.html
<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>
<body>
<div id=”result”></div>
<div id=”FormDiv”>
<form id="AddBook">
{{Form}}
</form>
<input type="submit" onclick="return ValidateBook();">
<div>
</body>
4.Ajax.js
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("FormDiv").innerHTML=""
}
else
{
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
}
}