Home > Net >  Django template user in queryset condition
Django template user in queryset condition

Time:08-19

I have the following Post and Follow models:

class Post(models.Model):
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    @property
    def followers(self):
        return self.follow_set.filter(post=self).values_list('user', flat=True)


class Follow(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

I tried the following code in shell to check for data in .followers property:

>>> from posts.models import Post
>>> x= Post.objects.get(id=22)
>>> x.followers
<QuerySet [1]>

What I ultimately want is to check if the authenticated user is among the followers. I have the following template code:

{% if user in object.followers %}
<a href="#">Unfollow</a>
{% else %}
<a href="#">Follow</a>
{% endif %}

The problem I have is that {% if user in object.followers %} always evaluates to False. P.S.: I always log-in the user id=1 (same as the queryset result from above).

CodePudding user response:

Use

{% if user in object.followers.all %}

CodePudding user response:

Nevermind. I just realized my mistake.

{% if user.id in object.followers %}
  • Related