Python - check if user is on command or not.

I have a model in which teams and participants are stored. I want to check if the requested user is in this command or not. How to do it?

Model

class TeamPlayer(models.Model): team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE) player = models.OneToOneField(User, related_name='player', on_delete=models.CASCADE) approved = models.BooleanField(default=False) 

Template

 {% if request.user in object.players.all %} <a href="{% url 'teams:leave' pk=object.id %}" class="btn btn-warning">Leave</a> {% else %} <a href="{% url 'teams:join' pk=object.id %}" class="btn btn-success">Join</a> {% endif %} 

The view is simply a simple DetailView .

+5
source share
2 answers

You have 1-on-1, so it should be

 players = TeamPlayer.object.all() if request.user.player in players # Do what you need to 

or in the template

 {% if request.user.player in players %} 

provided that players sent to the template

When he is one on one, he always user.player receives the associated player and player.user for the corresponding user.

+1
source

If you want to do this in a template, simply use the teamplayer_set command as follows:

 {% if request.user in object.teamplayer_set.all %} 
0
source

Source: https://habr.com/ru/post/1275273/


All Articles