Answer the question
In order to leave comments, you need to log in
How to work with likes in Django?
Guys, hello everyone.
Task:
Every article has likes in every comment (thumbs up, thumbs down). The task is to make sure that each user can put only one like per article or per comment.
Implementation options:
1) hang a cookie / session that will turn off the likes panel for the user who has already clicked on it.
2) Make a Forenkey for each object and write down the username of those who like it there. And already check through the database.
The second option looks more reliable, but there is a question about implementation.
Answer the question
In order to leave comments, you need to log in
1) If likes are placed without authorization, this is already unreliable. There is no way to separate the user if he clears cookies / changes browser / logs in from another IP address (very important now, in the age of the mobile Internet).
2) With authorization: hang M2M to the user on the object that they like.
Here it is:
class Video(models.Model):
thumbnumber = models.IntegerField(default=0, help_text="Начинается с 0", verbose_name="Число лайков")
likedone = models.ManyToManyField(User, related_name='users_video_main')
def upvideolike(request, add_id):
if request.user.is_authenticated():
video_item = Video.objects.get(id = add_id)
user_tags = User.objects.filter(users_video_main = add_id)
current_user = request.user
if current_user not in user_tags:
try:
video_item = Video.objects.get(id = add_id)
video_item.thumbnumber +=1
video_item.likedone.add(current_user)
video_item.save()
return redirect('/video'+ add_id)
except ObjectDoesNotExist:
return redirect('/video'+ add_id)
else:
return redirect('/video'+ add_id)
else:
return redirect('/video'+ add_id)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question