Reputation:
I created a Blog app, and i want to add a Like button to each post in the Blog, how can i do this ? how can i make this happen in view and the template ?
the models:
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Photo, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
the view:
def viewPhoto(request, pk):
post = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
return render(request, 'photo.html', {'photo': photo, 'post': post })
Upvotes: 0
Views: 55
Reputation: 1001
In other to use the like functionality you do something like this, but i hope you know how to work the frontend part, in your html?
def like(request, pk):
post = Photo.objects.get(pk=pk)
liked= False
like = Like.objects.filter(user=request.user, post=post)
if like:
like.delete()
else:
liked = True
Like.objects.create(user=request.user, post=post)
resp = {
'liked':liked
}
response = json.dumps(resp)
return redirect('') # redirect to any url after the object has been liked
return HttpResponse(response,content_type = "application/json")
You would need to put the liked object in any view that would prefer to have the like functionality:
def viewPhoto(request, pk):
post = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
liked = [i for i in Photo.objects.all() if Like.objects.filter(user=request.user, post=i)]
return render(request, 'photo.html', {'photo': photo, 'post': post ,'liked':liked})
Html template this is just to give you an idea on how to do that in your html , since i don't no what type of script or css you are using. so the button might not look like a thumb in your case.
<button class="btn btn-white mr-3 like" id="{{ post.id }}">
{% if post in liked %}
<a href="{% url 'blog:like' post.pk %}" id="likebtn{{ post.pk }}"
class="flex items-center space-x-2">
<div> Unlike</div>
</a>
{% else %}
<a href="{% url 'blog:like' post.pk %}" id="likebtn{{ post.pk }}" class="flex items-center space-x-2">
<div>Like</div>
</a>
{% endif %}
</button>
Upvotes: 0