Reputation: 8897
I have a specific problem with one method of my model. I'm building a "question-answer" site, like Stack Overflow.
I have this model for Answer (hide other fields):
class Answer(models.Model):
like = models.ManyToManyField(CustomUser, related_name='likes')
@property
def total_likes(self):
return self.like.count()
@property
def user_liked(self, request):
user = request.user
if self.like.filter(id=user.id).exists():
return True
else:
return False
So, in my view I realize this logic: when user clicks the "like" button, his object is added to the like-user
table, from ManyToMany
field; when he clicks again, his record is deleted.
I need to check in my template next logic: request.user clicked this answer or no. So I add method in model, and try to check in loop:
in view:
answer = Answer.objects.all()
...
{% for item in answer %}
{% if item.user_liked == True %}
...
This method doesn't work. How can I fix this? Or maybe you know other solutions for my problem?
Upvotes: 2
Views: 291
Reputation: 7049
This is better suited as a template tag:
Create a python package called templatetags in your app folder, then create a file called something like custom_tags.py, and in that file put:
from django import template
register = template.Library()
@register.filter()
def user_liked(answer, user):
is_liked = Answer.objects.filter(id=answer.id, user=user)
if is_liked:
return True
else:
return False
then in the template:
{% load custom_tags %}
{% if item|user_liked:request.user %}
Upvotes: 2