Use Ajax simply with Django

Tram Ho

1. General introduction

AJAX has now become an important part of web applications. AJAX also helps Django greatly in increasing efficiency and saving users time. All popular services use it one way or another. Apps like Facebook, Twitter, Instagram, Gmail, Google Maps, Spotify, etc. cannot work without AJAX.

You will have to use AJAX code at some point. Even Google’s search engine uses AJAX. You might have seen those search terms in the search bar while typing, which are results generated by AJAX.

2. AJAX in Django

We talked briefly about AJAX and how it is present on web pages. Now, let’s find out why we need AJAX in Django. AJAX is an acronym for Asynchronous JavaScript and XML (JavaScript and XML are asynchronous). It is a combination of technologies made to solve essential problems. It uses XMLHttpRequest objects to transmit and receive data.

The problem that AJAX solves

  • Request from your browser to reload the page.
  • The server receives and responds with the newly added messages.
  • The process continues every time you want to read a new mail.

This approach is time consuming and inefficient. The problem becomes more serious when the recipient requests an urgent response. Obviously, it was a real situation for websites before 2003.

In late 2003, all browsers solved the problem using XHR. XHR stands for XMLHttpRequest (XMLHttpRequest objects). Browsers use the XHR object to communicate with the server. Transfer occurred without reloading the entire page. The XMLHttpRequest API stands behind the processing of XHR requests.

Now, almost all browsers have XMLHttpRequest API. This makes applications like Gmail and Google Maps a reality.

How AJAX works in Django

AJAX is really just a combination of 2 JavaScript objects and XHR. The concept is simple:

  • JavaScript code on the client – The browser will make a request when an event occurs on the web page. The JavaScript will create an XHR object and send it as request object to the server. The XHR object contains some JavaScript data / objects. The XHR object also contains the URL or the name of the call-back function on the server.
  • The request is processed by the server with a callback function – the corresponding View function or callback function will handle the request. It will send a respone success or failure. Because the request is asynchronous, the rest of the source code is executed without interruption. At that time, the server will process the request.
  • Response returned as success or failure – A successful response may contain some server data in many formats such as:
    1. Text format
    Html Format (This section contains HTML elements).
    2. JSON format
    JSONP format (also JSON but only when the response comes from another domain).
    Script (This section contains some JavaScript that will be changed in the page).
    3. XML format
    Similarly, a failure response can also be formatted.
  • JavaScript will execute according to the response received – Normally, AJAX will execute based on data from the server. We can change the HTML components or run some JavaScript. Many things can use it.

3. An example of using AJAX in practice

In this article, we will create a simple website application that manages friends list using AJAX in Django.

Initial setup

We will use the jQuery library to easily implement JavaScript; moreover, we will also use Bootstrap 4 to make the application work better.

Below is the base.html template, which includes the jQuery library and the bootstrap framework. Make sure you include these links and scripts correctly. Also, note the content blocks and javascript , which will be used later.

base.html

I assume that you already know how to set up Django. If not, or if you are new to Django, please follow the Django documentation to get the initial setup.

Embark on the Code

In this article, we will use a real-time example to express POST and GET AJAX requests in Django.

We will use the ScrapBook script in which the user can create a friend and the application will display it flexibly. It will also check if the nickname is used or not by sending a GET request to the server.

Start by creating a Django application called “my_app” with the startapp command. Make sure you run the following manage.py command where the manage.py file exists, that is, in your project directory.

$ python manage.py startapp my_app

After creating the Django application, make sure you add it in INSTALLED_APPS in the settings.py file.

Create Models

Let’s create an example model for a Friend with the minimum number of properties in the models.py file

After creating models, perform makemigations and migrate by running the following commands.

Then run Django server.

$ python manage.py runserver

POST Request

To submit the form, we need to make a POST request to the server with all the values ​​of the form filled by the user.

1. Create Forms

Create the Django form by inheriting the ModelForm . In FriendForm , I changed the dob field and activated the DateField utility with some changes for the year. Also note that in the __init__ method, I updated an HTML attribute with the form-control for every form field so that Bootstrap is enabled on every field.

Finally, in the Meta subclass, I included the method class and the fields that were likely to be displayed.

Note that I have created a new file named forms.py in my application directory, with the following content:

2. Create Views

After creating the form, import FriendForm into the views. There are 2 views that need to be considered in this section, and they are indexView and postFriend .

  • indexView create object FriendForm , taking all the objects from the database friends and send them to index.html template, we will discuss it later.
  • postFriend is AJAX POST view, which handles POST request. You will notice that it is similar to the normal view, but with some changes, such as JsonResponse and serialize . We use these methods because this is an AJAX view, so we only need to deal with JSON.

The contents of the views.py file are as follows:

3. Create URLs

For the views above, create a URL for each view. Note the name given to the postFriend path, which will be used in the template mentioned later in this article.

The content of urls.py file is as follows:

4. Create Templates

Now that you have created the backend, let’s move on to the frontend of this article.

In index.html , we will first extend from base.html , which was mentioned earlier in this article. Moreover, we will write the content inside the blocks.

The template is divided into two parts. The first part renders the form, the second part displays the friends objects previously stored in the table.

index.html

Now move on to the JavaScript section of this article.

When submitting the form, we will serialize the form’s data and make an AJAX POST request, then send it to the server.

With the request successful, add a new row to the table.

Note that we used the reversed URL , mentioned in urls.py This helps you not to write hard URLs.

You can put this reversed URL tag into the HTML property and then fetch the following property. Put this JavaScript code into the js file.

index.html

GET Request

Now let’s move on to GET Request. In our current scenario, before submitting the form, we can check if a nickname already exists in the database by sending the entered nickname back to the server.

The following is a screenshot of what we will build in this section.

1. Create Views

Let’s create a view for this scenario. In view checkNickName , we first get the nickname that was sent by the AJAX request and then check to see if any friends have this nickname in the database. If it already exists, then we return it with a value of False, otherwise it is True.

2. Create URLs

For the above view, create a URL named validate_nickname .

3. Create Templates

Now, write the AJAX GET request for the focusout event of the nick_name input nick_name by taking the current nick_name value and sending it to the server.

After a successful GET request, notify if nick_name is accepted or not.

BONUS: Using Class-based Views

If you have some experience with Django, then you probably know that you can create views by function and by Class. Most developers are confused about how to use them and when to use them. So, in this short article, convert the above FBV (function based view) code to the CBV (class based view) code.

In this section, I will combine the indexView and postFriend functions into a single class called FriendView , inherit the View class and have two methods, get and post , respectively.

The contents of the views.py file are as follows:

Please write urlpattern for CBV discussed above. The content of urls.py file is as follows:

To convert from FBV to CBV, you need to change the reverse URL pattern as well.

index.js

4. Conclusion

AJAX is the best way to perform asynchronous tasks in Django, at least on a small scale. If you want to perform an asynchronous task on a larger scale, you can do socket programming in Django or use front-end JavaScript libraries like Angular, Vue or React.

Reference source

Share the news now

Source : Viblo