Book Image

Django: Web Development with Python

By : Aidas Bendoraitis, Samuel Dauzon, Arun Ravindran
Book Image

Django: Web Development with Python

By: Aidas Bendoraitis, Samuel Dauzon, Arun Ravindran

Overview of this book

Data science is hot right now, and the need for multitalented developers is greater than ever before. A basic grounding in building apps with a framework as minimalistic, powerful, and easy-to-learn as Django will be a useful skill to launch your career as an entrepreneur or web developer. Django is a web framework that was designed to strike a balance between rapid web development and high performance. This course will take you on a journey to become an efficient web developer thoroughly understanding the key concepts of Django framework. This learning path is divided into three modules. The course begins with basic concepts of the Django framework. The first module, Django Essentials, is like a practical guide, filled with many real-world examples to build highly effective Django web application. After getting familiar with core concepts of Django, it's time to practice your learning from the first module with the help of over 90 recipes available in this module. In the second module, Web Development with Django Cookbook, you'll learn varying complexities to help you create multilingual, responsive, and scalable websites with Django. By the end of this module, you will have a good understanding of the new features added to Django 1.8 and be an expert at web development processes.The next step is to discover the latest best practices and idioms in this rapidly evolving Django framework. This is what you'll be learning in our third module, Django Design Patterns and Best Practices. This module will teach you common design patterns to develop better Django code. By the end of the module, you will be able to leverage the Django framework to develop a fully functional web application with minimal effort.
Table of Contents (6 chapters)

Chapter 11. Using AJAX with Django

AJAX is an acronym for Asynchronous JavaScript and XML. This technology allows a browser to asynchronously communicate with the server using JavaScript. Refreshing the web page is not necessarily required to perform an action on the server.

Many web applications have been released that run on AJAX. A web application is often described as a website containing only one page and which performs all operations with an AJAX server.

If you are not using a library, using AJAX requires a lot of lines of code to be compatible with several browsers. When including jQuery, it is possible to make easy AJAX requests while at the same time being compatible with many browsers.

In this chapter, we will cover:

  • Working with JQuery
  • JQuery basics
  • Working with AJAX in the task manager

Working with jQuery

jQuery is a JavaScript library designed to effectively manipulate the DOM of the HTML page. The DOM (Document Object Model) is the internal structure of the HTML code, and jQuery greatly simplifies the handling.

The following are some advantages of jQuery:

  • DOM manipulation is possible with CSS 1-3 selectors
  • It integrates AJAX
  • It is possible to animate the page with visual effects
  • Good documentation with numerous examples
  • Many libraries have been created around jQuery

jQuery basics

In this chapter, we use jQuery to make AJAX requests. Before using jQuery, let's understand its basics.

CSS selectors in jQuery

CSS selectors used in style sheets can effectively retrieve an item with very little code. This is a feature that is so interesting that it is implemented in the HTML5 Selector API with the following syntax:

item = document.querySelector('tag#id_content');

jQuery also allows us to use CSS selectors. To do the same thing with jQuery, you must use the following syntax:

item = $('tag#id_content');

At the moment, it is better to use jQuery than the Selector API because jQuery 1.x.x guarantees great compatibility with older browsers.

Getting back the HTML content

It is possible to get back the HTML code between two tags with the html() method:

alert($('div#div_1').html());

This line will display an alert with the HTML content of the <div id="div_1"> tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val() method.

Setting HTML content in an element

Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.

Thus, the following instruction will add a button in the div tag:

$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');

Looping elements

jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each() method as shown in the following example:

var cases = $('nav ul li').each(function() {
  $(this).addClass("nav_item");
});

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

CSS selectors in jQuery

CSS selectors used in style sheets can effectively retrieve an item with very little code. This is a feature that is so interesting that it is implemented in the HTML5 Selector API with the following syntax:

item = document.querySelector('tag#id_content');

jQuery also allows us to use CSS selectors. To do the same thing with jQuery, you must use the following syntax:

item = $('tag#id_content');

At the moment, it is better to use jQuery than the Selector API because jQuery 1.x.x guarantees great compatibility with older browsers.

Getting back the HTML content

It is possible to get back the HTML code between two tags with the html() method:

alert($('div#div_1').html());

This line will display an alert with the HTML content of the <div id="div_1"> tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val() method.

Setting HTML content in an element

Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.

Thus, the following instruction will add a button in the div tag:

$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');

Looping elements

jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each() method as shown in the following example:

var cases = $('nav ul li').each(function() {
  $(this).addClass("nav_item");
});

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

Getting back the HTML content

It is possible to get back the HTML code between two tags with the html() method:

alert($('div#div_1').html());

This line will display an alert with the HTML content of the <div id="div_1"> tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val() method.

Setting HTML content in an element

Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.

Thus, the following instruction will add a button in the div tag:

$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');

Looping elements

jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each() method as shown in the following example:

var cases = $('nav ul li').each(function() {
  $(this).addClass("nav_item");
});

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

Setting HTML content in an element

Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.

Thus, the following instruction will add a button in the div tag:

$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');

Looping elements

jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each() method as shown in the following example:

var cases = $('nav ul li').each(function() {
  $(this).addClass("nav_item");
});

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

Looping elements

jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each() method as shown in the following example:

var cases = $('nav ul li').each(function() {
  $(this).addClass("nav_item");
});

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

Importing the jQuery library

To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:

  • Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
  • Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.

In this chapter, we will host jQuery on our web server to not be dependent on a host.

We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js file.

Then, you must add the following line in the head tag of the base.html file:

<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script>
{% block head %}{% endblock %}

With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head block from the template which extends base.html.

Working with AJAX in the task manager

In this section, we will modify the page that displays the list of tasks for deleting the tasks to be carried out in AJAX. To do this, we will perform the following steps:

  1. Add a Delete button on the task_list page.
  2. Create a JavaScript file that will contain the AJAX code and the function that will process the return value of the AJAX request.
  3. Create a Django view that will delete the task.

We will add the Delete button by modifying the tasks_list.html template. To do this, you must change the for task in task loop in tasks_list as follows:

{% for task in tasks_list %}
  <tr id="task_{{ task.id }}">
    <td><a href="{% url "task_detail" task.id %}">{{ task.title }}</a></td>
    <td>{{ task.description|truncatechars:25 }}</td>
    <td><a href="{% url "update_task" task.id %}">Edit</a></td>
    <td><button onclick="javascript:task_delete({{ task.id }}, '{% url "task
_delete_ajax" %}');">Delete</button></td>
  </tr>
{% endfor %}

In the preceding code, we added an id property to the <tr> tag. This property will be useful in the JavaScript code to delete the task line when the page will receive the AJAX response. We also replaced the Delete link with a Delete button that executes the JavaScript task_delete() function. The new button will call the task_delete() function to execute the AJAX request. This function accepts two parameters:

  • The identifier of the task
  • The URL of the AJAX request

We will create this function in the static/javascript/task.js file by adding the following code:

function task_delete(id, url){
  $.ajax({
    type: 'POST', 
    // Here, we define the used method to send data to the Django views. Other values are possible as POST, GET, and other HTTP request methods.
    url: url, 
    // This line is used to specify the URL that will process the request.
    data: {task: id}, 
    // The data property is used to define the data that will be sent with the AJAX request.
    dataType:'json', 
    // This line defines the type of data that we are expecting back from the server. We do not necessarily need JSON in this example, but when the response is more complete, we use this kind of data type.
    success: task_delete_confirm,
    // The success property allows us to define a function that will be executed when the AJAX request works. This function receives as a parameter the AJAX response.
    error: function () {alert('AJAX error.');} 
    // The error property can define a function when the AJAX request does not work. We defined in the previous code an anonymous function that displays an AJAX error to the user.
  });
}
function task_delete_confirm(response) {
  task_id = JSON.parse(response); 
  // This line is in the function that receives the AJAX response when the request was successful. This line allows deserializing the JSON response returned by Django views.
  if (task_id>0) {
    $('#task_'+task_id).remove(); 
    // This line will delete the <tr> tag containing the task we have just removed
  }
  else {
    alert('Error');
  }
}

We must add the following lines after the title_html block in the tasks_list.html template to import task.js in the template:

{% load static %}
{% block head %}
  <script src="{% static 'javascript/task.js' %}"></script>
{% endblock %}

We must add the following URL to the urls.py file:

  url(r'^task-delete-ajax$', 'TasksManager.views.ajax.task_delete_ajax.page', name="task_delete_ajax"),

This URL will use the views contained in the view/ajax/task_delete_ajax.py file. We must create the AJAX module with the __init__.py file and our task_delete_ajax.py file with the following content:

from TasksManager.models import Task
from django.http import HttpResponse
from django import forms
from django.views.decorators.csrf import csrf_exempt
# We import the csrf_exempt decorator that we will use to line 4.
import json
# We import the json module we use to line 8.
class Form_task_delete(forms.Form):
# We create a form with a task field that contains the identifier of the task. When we create a form it allows us to use the Django validators to check the contents of the data sent by AJAX. Indeed, we are not immune that the user sends data to hack our server.
  task       = forms.IntegerField()
@csrf_exempt
# This line allows us to not verify the CSRF token for this view. Indeed, with AJAX we cannot reliably use the CSRF protection.
def page(request):
  return_value="0"
  # We create a variable named return_value that will contain a code returned to our JavaScript function. We initialize the value 0 to the variable.
  if len(request.POST) > 0:
    form = Form_task_delete(request.POST)
    if form.is_valid():
    # This line allows us to verify the validity of the value sent by the AJAX request.
      id_task = form.cleaned_data['task']
      task_record = Task.objects.get(id = id_task)
      task_record.delete()
      return_value=id_task
      # If the task been found, the return_value variable will contain the value of the id property after removing the task. This value will be returned to the JavaScript function and will be useful to remove the corresponding row in the HTML table.
  # The following line contains two significant items. The json.dumps() function will return a serialized JSON object. Serialization allows encoding an object sequence of characters. This technique allows different languages to share objects transparently. We also define a content_type to specify the type of data returned by the view.
  return HttpResponse(json.dumps(return_value), content_type = "application/json")

Summary

In this chapter, we learned how to use jQuery. We saw how to easily access the DOM with this library. We also created an AJAX request on our TasksManager application and we wrote the view to process this request.

In the next chapter, we will learn how to deploy a Django project based on the Nginx and PostgreSQL server. We will see and discuss the installation step by step.