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 JsonResponse
from django.views.decorators.http import require_POST
from common.decorators import ajax_required
from .models import Contact

@ajax_required
@require_POST
@login_required
def 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'})
except User.DoesNotExist:
return JsonResponse({'status':'ko'})
return JsonResponse({'status':'ko'})

The user_follow view is quite similar to the image_like view we created before. Since we are using a custom intermediary model for the users' many-to-many relationship, the default add() and remove() methods of the automatic manager of ManyToManyField are not available. We use the intermediary Contact model to create or delete user relationships.

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

path('users/follow/', views.user_follow, name='user_follow'),

Ensure that you place the preceding pattern before the user_detail URL pattern. Otherwise, any requests to /users/follow/ will match the regular expression of the user_detail pattern and that view will be executed instead. Remember that, in every HTTP request, Django checks the requested URL against each pattern in order of appearance and stops at the first match.

Edit the user/detail.html template of the account application and append the following code to it:

{% block domready %}
$('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "user_follow" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok') {
var previous_action = $('a.follow').data('action');

// toggle data-action
$('a.follow').data('action',
previous_action == 'follow' ? 'unfollow' : 'follow');
// toggle link text
$('a.follow').text(
previous_action == 'follow' ? 'Unfollow' : 'Follow');

// update total followers
var previous_followers = parseInt(
$('span.count .total').text());
$('span.count .total').text(previous_action == 'follow' ?
previous_followers + 1 : previous_followers - 1);
}
}
);
});
{% endblock %}

The preceding code is the JavaScript code to perform the AJAX request to follow or unfollow a particular user and also to toggle the follow/unfollow link. We use jQuery to perform the AJAX request and set both the data-action attribute and the text of the HTML <a> element based on its previous value. When the AJAX action is performed, we also update the total followers count displayed on the page. Open the user detail page of an existing user and click on the FOLLOW link to test the functionality we just built. You will see that the follower's count gets increased:

..................Content has been hidden....................

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