Using Ajax Calls in Django Framework

Django is a high level Python based web framework. In order to create a working project in Django, the basic components includes a views which is a python file with the backend logic, an html template that would render all static components and a urls file that links these two python and html files. But what if we want to add some dynamic content to our html page or update the page on fly. We don’t want to refresh it each time we receive a new input from user or process it. For this purpose we use Ajax which uses XMLHTTPRequest to update content of the existing html page without refreshing it. Lets take a scenario where Ajax is used within Django framework to dynamically update the contents of the page. For example, say our html template loads the first time with a div that has a form to enter number of records to retrieve from database. Based on the user input, we display the contents using ajax and not reloading the entire page.

The initial base.html would render all static content and include all necessary jquery and css files and this would be inherited within our specific html template say myreport.html. This myreport.html would look something like this.

# extends 'base.html'
{% block content %}
<!-- This block is loaded initially to ask for user input -->
<div class="row-fluid">
	<div class="span12">
		<div class="widget-box">
			<div class="widget-title">
				<span class="icon">
					<i class="icon-list-alt"></i>
				<h5>Input Values from User</h5>
            <div class="widget-content">
                Enter Number Of Records: <input type='text' name='numrecs' id='num_recs'>
                <button type="submit" value="View Report" onclick="send_request()>View Report</button>
<!-- This block is loaded only after ajax call retrieves the data from table -->
<div class="row-fluid" id='example_table' style="display:none;">
	<div class="span12">
		<div class="widget-box">
			<div class="widget-title">
				<span class="icon">
					<i class="icon-list-alt"></i>
				<h5>Table Name</h5>
            <div class="widget-content"></div>
			<div id="placeholder"></div>
{% endblock content %}	

{% block script %}
<script id="source" language="javascript" type="text/javascript">
//This sends the user input on number of recs to views
function delete_request()
    params = {'records':$("#num_recs").val()};
    var serializedData = jQuery.param( params );
	  type: "POST",
	  url: "{{ lib.url('json_function') }}",
	  data: serializedData,
	  success: function(return_val){show_table(return_val[0]);},
	  dataType: 'JSON'
//renders the report
function show_table(data)
	var str="";
	var i=0;
	var j=0;
		str="<table class='table' id='example_table'><thead><tr>";
			var row=jQuery.parseJSON([i]);
	//table initialization
	var oTable = $('#example_table').dataTable( {
	    "bJQueryUI": true,
	    "bRetrieve": true,
	    "sDom": '<"F"lfT>t<"F"p>',
	    "iDisplayLength": 10,
	    "sPaginationType": "full_numbers",
	    "aaSorting": [[ 0, "desc" ]],
	    "oTableTools": {
			"sSwfPath": "/static/plugins/TableTools/media/swf/copy_csv_xls.swf",
			"aButtons": [
					"sExtends":    "collection",
					"sButtonText": 'Export <span class="caret" />',
					"aButtons":    [ "csv", "xls", "pdf" ]
	} );  
{% endblock script %}

Next within our we will create the function to render this html template and the function that will handle the ajax requests.

'''This page returns nothing except rendering the static form for user input'''
def myreport(request):
    return {
'''This handles the ajax request'''
def json_function(request):
	report = []
	records_to_retrieve = 0
	url = request.REQUEST
	fields = ['fieldA','fieldB','fieldC','fieldD']
	headers = ['A','B','C','D']
	if 'info_request' in url and 'records' in url:
		records_to_retrieve = int(url['records'])
		temp = DatabaseModel.objects.all().values(*fields)[:records_to_retrieve]
		records = CapacityDemand.objects.get(id = int(url['demand_id']))
		for row in records:
	response = json.dumps(jdata)
	return HttpResponse(response, mimetype="text/plain")

And in the end we link these two files in the file as follows:

    url(r'^myreport/$', 'appname.views.myreport', name='myreport'),
    url(r'^json_function/$', 'appname.views.json_function', name='json_function'),