Book Image

Django 3 By Example - Third Edition

By : Antonio Melé
Book Image

Django 3 By Example - Third Edition

By: Antonio Melé

Overview of this book

If you want to learn the entire process of developing professional web applications with Python and Django, then this book is for you. In the process of building four professional Django projects, you will learn about Django 3 features, how to solve common web development problems, how to implement best practices, and how to successfully deploy your applications. In this book, you will build a blog application, a social image bookmarking website, an online shop, and an e-learning platform. Step-by-step guidance will teach you how to integrate popular technologies, enhance your applications with AJAX, create RESTful APIs, and set up a production environment for your Django projects. By the end of this book, you will have mastered Django 3 by building advanced web applications.
Table of Contents (17 chapters)
15
Other Books You May Enjoy
16
Index

Adding AJAX actions with jQuery

Now let's add AJAX actions to your application. AJAX comes from Asynchronous JavaScript and XML, encompassing a group of techniques to make asynchronous HTTP requests. It consists of sending and retrieving data from the server asynchronously, without reloading the whole page. Despite the name, XML is not required. You can send or retrieve data in other formats, such as JSON, HTML, or plain text.

You are going to add a link to the image detail page to let users click on it in order to like an image. You will perform this action with an AJAX call to avoid reloading the whole page.

First, create a view for users to like/unlike images. Edit the views.py file of the images application and add the following code to it:

from django.http import JsonResponse
from django.views.decorators.http import require_POST
@login_required
@require_POST
def image_like(request):
    image_id = request.POST.get('id')
    action = request.POST.get...