Jack Ryan
Jack Ryan

Reputation: 17

All the users name who liked a post in django

I cannot show all the users name who liked the post in django. I have tried many ways to do that but its not working. my models.py:

class post(models.Model):
     title = models.CharField(max_length=100)
     image = models.ImageField(upload_to='post_pics', null=True, blank=True)
     video = models.FileField(upload_to='post_videos', null=True, blank=True)
     content = models.TextField()
     likes = models.ManyToManyField(User, related_name='likes', blank=True)
     date_posted = models.DateTimeField(default=timezone.now)
     author = models.ForeignKey(User, on_delete=models.CASCADE)

     def __str__(self):
         return self.title


     def delete(self, *args, **kwargs):
         self.image.delete()
         super().delete(*args, **kwargs)

     def get_absolute_url(self):
             return reverse ('blog-home')

in views.py :

def like_post(request):
# posts = get_object_or_404(Post, id=request.POST.get('post_id'))
    posts = get_object_or_404(post, id=request.POST.get('post_id'))
    is_liked = False
    if posts.likes.filter(id=request.user.id).exists():
        posts.likes.remove(request.user)
        is_liked = False
    else:
        posts.likes.add(request.user)
        is_liked = True

    return render(request, 'blog/home.html')

def post_likes(request, pk):
    posts = get_object_or_404(post, pk=pk)
    post_likes = posts.likes.all()
    context = {'post_likes': post_likes,}

    return render(request, 'blog/post_likes.html', context)

in urls.py:

path('post/<int:pk>/postlikes/', views.post_likes, name='post-likes'),

and in post_like.html:

{% extends "blog/base.html" %}
{% block content %}
{% for likes in posts %}
<p>{{ posts.likes.user.all }}</p>
{% endfor %}
{% endblock content %}

How can i see the usernames who liked the particular post?

Upvotes: 1

Views: 320

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You iterate over the post_likes, which are User objects, and then you render the user.username:

{% extends "blog/base.html" %}
{% block content %}
{% for user in post_likes %}
    <p>{{ user.username }}</p>
{% endfor %}
{% endblock content %}

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 2

Related Questions