Robert Li
Robert Li

Reputation: 7

Django if else template tag queryset not right

I want to display a "follow" button when the user is not following the project, and update the button once the user follows it.

I tried using the following template tags but it was always returning true.

Here is the model for projects people can follow, following includes a list of followers that currently following this project.

class Team(models.Model):
    following = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='followers',
        blank=True,
    )

These are the template tags I tried, but it always returns "Follow".

{% if not request.user in user.followers.all  %}
    <div class="progress-stats">
        <a href="{% url 'teams:follow' team.id %}">Follow</a>
    </div>
{% endif %}
{% if request.user in user.followers.all %}
     <div class="progress-stats">
         <a href="{% url 'teams:unfollow' team.id %}">Unfollow</a>
     </div>
{% endif %}

Upvotes: 0

Views: 137

Answers (2)

Kenneth M Burling Jr
Kenneth M Burling Jr

Reputation: 19

Try changing request.user to just user.

request.user exists in the views code. The system automatically provides user to the template code however.

request.user is either Null or None, I am not sure which, but it basically means that any time you search for it in a query, from the template, it is not going to be there. Thus not request.user in whatever is always going to be true.

Edit: Also, if you are providing 'user' to the template explicitly from the view, try changing it to something else. As I said above, the template code automatically provides user. It does not provide request.user. Non-existing variables, in most cases, are just going to silently fail, and return the appropriate default value for their particular presuemed data-type.

Upvotes: 0

user2390182
user2390182

Reputation: 73498

You want to check if the user is in the team's following:

<div class="progress-stats">
  {% if request.user in team.following.all %}
    <a href="{% url 'teams:unfollow' team.id %}">Unfollow</a>
  {% else %}
    <a href="{% url 'teams:follow' team.id %}">Follow</a>
  {% endif %}
</div>

As far as field naming goes, this would make more sense:

class Team(models.Model):
    followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='teams', blank=True)

Now, the users that follow a given team can be accessed via team.followers.all(), and a given user's teams via user.teams.all().

Upvotes: 1

Related Questions