How to Integrate Ajax With Django Applications

How do I integrate Ajax with Django applications?

Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).

Django is server-side. It means, say a client goes to a URL, you have a function inside views that renders what he sees and returns a response in HTML. Let's break it up into examples:

views.py:

def hello(request):
return HttpResponse('Hello World!')

def home(request):
return render_to_response('index.html', {'variable': 'world'})

index.html:

<h1>Hello {{ variable }}, welcome to my awesome site</h1>

urls.py:

url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello means a request to the hello() function, going to 127.0.0.1:8000/home will return the index.html and replace all the variables as asked (you probably know all this by now).

Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.

For example, an AJAX call to 127.0.0.1:8000/hello will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:

$.ajax({
url: '127.0.0.1:8000/hello',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});

The general process is this:

  1. The call goes to the URL 127.0.0.1:8000/hello as if you opened a new tab and did it yourself.
  2. If it succeeds (status code 200), do the function for success, which will alert the data received.
  3. If fails, do a different function.

Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>.

In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:

  1. Learn jQuery. I cannot stress this enough. You're gonna have to understand it a little to know how to handle the data you receive. You'll also need to understand some basic JavaScript syntax (not far from python, you'll get used to it). I strongly recommend Envato's video tutorials for jQuery, they are great and will put you on the right path.
  2. When to use JSON?. You're going to see a lot of examples where the data sent by the Django views is in JSON. I didn't go into detail on that, because it isn't important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don't want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
  3. Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That's a good process that helps you learn a lot as well.
  4. Use chrome's developer tools. Since AJAX calls are done in the background it's sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.
  5. CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.

That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.

Best way to integrate Django with an Ajax library

On python side, I'd suggest to look at piston and tastypie.

(Starting with AJAX + Django myself, I also found Dajax, but went with piston—felt more ‘unix-way’ for me, don't like these all-in-one solutions. Though piston wasn't updated for a long time now, so I'd recommend tastypie, which is actively maintained.)

EDIT. There's also a similar project, django-rest-framework. Never used it myself yet, it's pretty new.

Basically, these libs help you create a fully working read-write API for your models, so you can perform create-read-update-delete operations from your javascript via HTTP. You don't need to define any views or serializers. Instead, you define resources, which is a decent abstraction, I think.

And it usually takes just a few lines of code, especially if your resources are tied to models.

However, if you need something more complicated, you can rethink your design write your views. With class-based views, it's pretty easy, too. Take a look at this snippet for example.

django app with ajax for processing dataframe

I was able to achieve loading animation on a django app using Ajax POST instead of Ajax GET. Posting the code in case this shows up in search results.

fileprocessed.html

    <script>
var dataframe = JSON.parse("{{df|escapejs}}");
var replace_data = function(data){
$('#loading').remove()
$('#load_processed').DataTable({
columns:[
{title:'col1'},
{title:'col2'},
{title:'col3'},
{title:'col4'},
{title:'col5'},
{title:'col6'},
{title:'col7'},
{title:'col8'},
{title:'col9'},
{title:'col10'},
{title:'col11'},
{title:'col12'},
{title:'col13'},
{title:'col14'},
{title:'col15'},
{title:'col16'},
{title:'col17'},
{title:'col18'},
{title:'col19'},
{title:'col20'}
],
data: data
});

}
$(document).ready(function(){
$.ajax({
url: '/processing/',
type:'POST',
data: JSON.stringify(dataframe),
success: function(data){
replace_data(data)
}
})
})
</script>
<div id="loading">
<div id="img_div">
{% load static %}<img src="{% static "/img/hourGlass.gif" %}" alt="Hour Glass image, processing"/></div>
<p><b>Loading....</b></p>
</div>
<div id="success">
<table id="load_processed" class="display" width="100%">

</table>

The function that gets triggered when user clicks UI button,

def busy_indicator(request):
excel_file = request.FILES["excel_file"]
uploaded_data = pd.read_excel(excel_file)
df_json = uploaded_data.to_json()
return render(request,'myapp/file_processed.html',{'df':df_json})

The ajax calls the below function(url /processing shown in above ajax post code),

@csrf_exempt
def processing_file(request):
if request.is_ajax():
e1 = json.loads(request.body) #parses incoming json data
input_df = pd.DataFrame.from_dict(e1) #converts to df as my process script
#requires dataframe input
processed = gen.generate_output_columns(input_df)
output_validation = processed[const.OUTPUTCOLUMNSWITHVALIDATION]
excel_data = output_validation.values.tolist()
return HttpResponse(json.dumps(excel_data), content_type='application/json')#sends
#back json to ajax

Ajax Request to Django Application

Try using the following, and check the Django server log to check if has received a request, and what is the request status code.

$.ajax({
url: url,
data: data: {
username:username,
password:password,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
type: 'POST',
success: function(data) {
console.log(data.message);
},
error: function(data) {
console.log(data.message);
}
},


Related Topics



Leave a reply



Submit