Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Check if User Is in Many to Many User Field (template)

Tags:

python

django

I have a model:

class Projects(models.Model):
    name = models.CharField(max_length=200)
    users = models.ManyToManyField(User)

As you can see, the model contains a ManytoMany field with User model.

In my template, I want to check if the current authenticated user is in the Projects users field that was passed to the template:

@login_required
def index(request):

    projects = Projects.objects.all()

    context = {
        'projects' : projects
    }

    return render(request,'app/index.html',context)

The template code will look something like this:

{% for project in projects  %}

   {% if user is in project.user  %} {% endif %}

{% endfor %}

Any help will be appreciated!

like image 289
ceds Avatar asked Mar 21 '18 07:03

ceds


1 Answers

Almost:

{% for project in projects  %}
    {% if user in project.users.all  %}
    {% endif %}
{% endfor %}
like image 187
DavidRguez Avatar answered Nov 19 '22 19:11

DavidRguez