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 image_like(request):
image_id = request.POST.get('id')
action = request.POST.get('action')
if image_id and action:
try:
image = Image.objects.get(id=image_id)
if action == 'like':
image.users_like.add(request.user)
else:
image.users_like.remove(request.user)
return JsonResponse({'status':'ok'})
except:
pass
return JsonResponse({'status':'ko'})

We will use two decorators for our view. The login_required decorator prevents users that are not logged in from accessing this view. The require_POST decorator returns an HttpResponseNotAllowed object (status code 405) if the HTTP request is not done via POST. This way, we only allow POST requests for this view. Django also provides a require_GET decorator to only allow GET requests and a require_http_methods decorator to which you can pass a list of allowed methods as an argument.

In this view, we use two GET parameters:

  • image_id: The ID of the image object on which the user is performing the action
  • action: The action that the user wants to perform, which we assume to be a string with the value like or unlike

We use the manager provided by Django for the users_like many-to-many field of the Image model in order to add or remove objects from the relationship using the add() or remove() methods. Calling add(), that is, passing an object that is already present in the related object set does not duplicate it, and thus, calling remove(), passing an object that is not in the related object set does nothing. Another useful method of the many-to-many manager is clear(), which removes all objects from the related object set.

Finally, we use the JsonResponse class provided by Django, which returns an HTTP response with an application/json content type, converting the given object into a JSON output.

Edit the urls.py file of the images application and add the following URL pattern to it:

path('like/', views.image_like, name='like'),
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151