user2896120
user2896120

Reputation: 3282

Check if user is following user?

I have a DetailView which renders the profile page like so:

class ProfileView(DetailView):
    model = User
    slug_field = 'username'
    template_name = 'oauth/profile.html'
    context_object_name = 'user_profile' 

The User model contains fields about the user like id, username, email, password I also have another model that has a one to many relationship with this User model. It shows who the User is following like so:

class Following(models.Model):
    target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True)
    follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True)

    def __str__(self):
        return '{} is followed by {}'.format(self.target, self.follower)

Inside my template, I have the following logic:

<form method="post" action="">
       {% csrf_token %}
        {% if user in user_profile.followers.all %}
              <input type="submit" class="item profile-nav__follow-btn" value="Following">
        {% else %}
              <input type="submit" class="item profile-nav__follow-btn" value="Follow">
        {% endif %}
</form>

I'm trying to check if the user is following that specific user. However, even though it should be true, the Follow input button is shown instead. What is wrong with my logic? Why isn't the Following input button being shown instead?

Upvotes: 3

Views: 751

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

The problem is user_profile.followers.all will return list of Following instances, not users. And so user in user_profile.followers.all will not work. You can check follower with this query:

user_profile.followers.filter(follower=self.request.user).exists()

Since you cannot use this query in template you can override get_context_data and put result into context:

class ProfileView(DetailView):
    model = User
    slug_field = 'username'
    template_name = 'oauth/profile.html'
    context_object_name = 'user_profile' 

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['is_follower'] =  self.object.followers.filter(follower=self.request.user).exists()
        return context 

Not in template use variable is_follower instead:

{% if is_follower %}

Upvotes: 2

Related Questions