**post_detail.html**
{{post.total_likes}}
<form class="" action="{%url 'like_post' %}" method="post">
{%csrf_token%}
{% if is_liked %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-danger">DisLike</button>
{% else %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-primary">Like</button>
{% endif %}
</form>
**views.py**
def like_post(request):
post = get_object_or_404(Post,id=request.POST.get('post_id'))
is_liked=False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked=False
else:
post.likes.add(request.user)
is_liked=True
return HttpResponseRedirect(post.get_absolute_url())
class PostDetailView(DetailView):
model = Post
fields = ['likes']
def get_context_data(self,**kwargs):
post = self.get_object()
request = self.request
post.is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.is_liked = True
context = super().get_context_data(**kwargs)
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
return context
**urls.py**
from django.urls import path
from django.conf.urls import url
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
SearchResultView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='Blog-home'),
path('search/', SearchResultView.as_view(), name='search-result'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='Blog-about'),
path('like/',views.like_post,name="like_post"),
]
**models.py**
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
ikes = models.ManyToManyField(User,related_name='likes',blank=True)
def __str__(self):
return self.title
def total_likes(self):
return self.likes.count()
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
This is my code. It do not have any error the only problem is that the like button remain unchanged i.e, is liked seems to be always false. I used class based view for my post_detail and add get_context_data method to it.But i think this method is not working. So i need a write code for PostDetailView.Rest everything is working fine.Main issue is in PostDetailView is returning is_liked always false.
should i use function view instead?
The problem is here:
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
It is actually generating a dictionary like this:
{('total_likes', 'is_liked'): [100, True]}
Instead, update the context like this:
context.update({'total_likes': post.total_likes(), 'is_liked': post.is_liked})
return context