How to show whether user already liked object instance in Django
I have the following table in my Django model, Dishes and Likes. On my
home page I am showing a list of all the dishes in the database, and I
have a like button on each dish. For dishes that the user has liked I want
to indicate that they already liked it, so that they can unlike it and
vice versa. I have been trying different approaches for the last few days
but can't seem to figure anything out. Here is the code for my latest
unsuccessful attempt.
#dishes table
class Dishes(models.Model):
name = models.CharField(max_length=40, unique=True)
def liked(dish, user):
try:
user_upvoted = Likes.objects.get(dish=dish, user=user)
except:
user_upvoted = None
if user_upvoted:
return True
else:
return False
#upvotes
class Likes(models.Model):
dish = models.ForeignKey(Dishes)
user = models.ForeignKey(User)
date_added = models.DateTimeField(auto_now_add=True)
def home(request):
this_user = auth.models.User.objects.get(id=1)
dishes = models.Dishes.objects.all()
for dish in dishes:
models.Dishes.voted(dish, this_user)
`enter code here`return render_to_response('frontend/home.html', {
'dishes': dishes, })
No comments:
Post a Comment