[Answer]-How to add likes of an object for the given user

1👍

First you need to create a URL that targets the view. The URL would pass a forum_id as a URL parameter.

from datetime import datetime
from django.shortcuts import get_object_or_404

@login_required
def update_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like, _ = Like.objects.get_or_create(user=request.user, forum=forum, 
                   defaults={'liked_date': datetime.now()})
    #rest of the code here. 

This is one way. You could also do it in the way you thought of doing it, but you will have to manually control the duplicates that could get generated. (you could specify a unique_together on the ('forum', 'liked') )

and to delete

@login_required
def delete_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like = get_object_or_404(Like, user=request.user, forum=forum)
    like.delete()
    #rest of the code here. 

Leave a comment