[Answered ]-How make Like button in django using ajax

1👍

You can use JsonResponse (Django Docs) and create a simple view (Django Docs).

I am assuming that likes are many2many fields related to the User model.

Then you can use the following code:

views.py:

from django.http import JsonResponse

def add_remove_like(request, pk):
    data = {}
    video = Video.objects.get(pk=pk)

    if request.method == "POST":
        user = request.user
        if video.likes.filter(id=user.id).exists():
            liked = False
            video.likes.remove(user)
        else:
            video.likes.add(user)
            liked = True


    data["count"] = video.likes.count()
    data["liked"] = liked
    return JsonResponse(data) 

.html:

$("#my-like-form").submit(function(e){
    e.preventDefault(); 

    var form = $(this);
    let url = form.attr("action");

    $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(),
        dataType: "json",
        success: function(response) {
            var btn = form.find("button[type='submit']");

            if (response.liked) {
                console.log('Hello');
                btn.css("color", "blue");
            } else {
                btn.css("color", "black");
            }
            btn.find("span").text(response.count)
        }
    })
})

urls.py:

from django.contrib.auth.decorators import login_required

path('account/video/<int:pk>/like', login_required(views.add_remove_like), name='add_remove_like'),

Note: I renamed the view to add_remove_like

👤NKSM

Leave a comment