I'm trying to create a page where people can see the highest rated article in the homepage but I don't know how to use likes to do so.
My post model
class Post(models.Model):
title = models.CharField(max_length=225)
post_image = models.ImageField(null=True, blank=True, upload_to="images/")
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('post-detail', args=(str(self.id)),)
my views.py
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('post-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
class PostDetail(DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, *args, **kwargs):
context = super(PostDetail, self).get_context_data()
current_post = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = current_post.total_likes()
liked = False
if current_post.likes.filter(id=self.request.user.id).exists():
liked = True
context['total_likes'] = total_likes
context['liked'] = liked
return context
Thanks in advance! ...................................................................................................
question from:https://stackoverflow.com/questions/65944103/django-order-by-highest-number-of-likes-in-homepage