Book Image

Django 2 by Example

By : Antonio Melé
Book Image

Django 2 by Example

By: Antonio Melé

Overview of this book

If you want to learn the entire process of developing professional web applications with Django 2, then this book is for you. You will walk through the creation of four professional Django 2 projects, teaching you how to solve common problems and implement best practices. You will learn how to build a blog application, a social image bookmarking website, an online shop and an e-learning platform. The book will teach you how to enhance your applications with AJAX, create RESTful APIs and set up a production environment for your Django 2 projects. The book walks you through the creation of real-world applications, solving common problems, and implementing best practices. By the end of this book, you will have a deep understanding of Django 2 and how to build advanced web applications.
Table of Contents (15 chapters)

Adding AJAX actions with jQuery

Now, we will add AJAX actions to our application. AJAX comes from Asynchronous JavaScript and XML. This term encompasses 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.

We will add a link to the image detail page to let users click on it in order to like an image. We will perform this action with an AJAX call to avoid reloading the whole page. First, we will 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...