Building an AJAX view to follow users

We will create a simple view to follow/unfollow a user using AJAX. Edit the views.py file of the account application and add the following code to it:

from django.http import JsonResponsefrom django.views.decorators.http import require_POSTfrom common.decorators import ajax_requiredfrom .models import Contact@ajax_required@require_POST@login_requireddef user_follow(request):    user_id = request.POST.get('id')    action = request.POST.get('action')    if user_id and action:        try:            user = User.objects.get(id=user_id)            if action == 'follow':                Contact.objects.get_or_create(                    user_from=request.user,                    user_to=user)            else:                Contact.objects.filter(user_from=request.user,                                       user_to=user).delete() return JsonResponse({'status':'ok'}) ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.