I have like and dislike for the article. Like and dislike is working perfectly, but the only problem is when I like the article I stay on the same page, I got redirected to the top of the page. All I want is to stay not only on the page but also on the same position of the page. All my articles have images so to read the entire article we have to scroll down and then the like button is at the end of the article. Here are some details.
post_detail page(like button)
<form action="{% url 'like_post' single_post.category.slug single_post.slug %}" method="POST">
{% csrf_token %}
<button type="submit" name="like_btn" value={{single_post.id}} class="ui red button like_btn" >
<i class="heart icon"></i> Like ({{single_post.total_likes}})
</button>
</form>
urls.py
path('<slug:category_slug>/<slug:post_slug>', views.post_detail , name="post_detail"),
path('like/<slug:category_slug>/<slug:post_slug>', views.like_post, name="like_post")
post model
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=100)
image = models.ImageField(upload_to = 'photos/post_image/%Y/%m/%d/', default="../static/images/pp2.jpg")
category = models.ForeignKey(Category, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name='post_likes')
description = FroalaField()
views = models.IntegerField(default=0)
comments = GenericRelation(Comment)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
return super(Post, self).save(*args, **kwargs)
def total_likes(self):
return self.likes.count()
def get_url(self):
return reverse("post_detail", args=[self.category.slug, self.slug])
def __str__(self):
return self.title
views.py
def like_post(request,category_slug, post_slug):
post = get_object_or_404(Post, id=request.POST.get('like_btn'))
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=[category_slug, post_slug]))