Check if User is in Many2Many field

514 views Asked by At

I have the following model with a m2m field where logged in Users can show interest in a publication:

models.py

from django.db import models

class Publication:
  title = models.CharField(max_lenth=512)
  users_interested = models.ManyToManyField(User)

views.py

from django.shortcuts import render
from django.views import View
from .models import Publication

class listPublicationView(View):
  def get(self, request, *args, **kwargs):

    publications = Publication.objects.all()

    return render(request, "base.html", {'publications': publications})

Now i try to produce a "i am already interested" in the template when a logged in user is already interested in the publication:

base.html

{% for publication in publications %}

  {{publication.title}}

  {% if currently logged in User is interested in publication (check users_interested) %}
      i am already interested
  {% endif %}

{% endfor %}

I think about something like this:

{% if user.id in publication.users_interested__id %}
2

There are 2 answers

1
fuser60596 On BEST ANSWER

This seems to look like a good solution:

models.py

from django.db import models

class Publication:
  title = models.CharField(max_lenth=512)

  #added a reverse accessor
  users_interested = models.ManyToManyField(User, related_name='users_interested')

view.py

from django.shortcuts import render
from django.views import View
from .models import Publication

class listPublicationView(View):
  def get(self, request, *args, **kwargs):

    publications = Publication.objects.all()

    # create a set of group IDs that this user is a part of
    current_user = request.user
    user_publication_set = set(current_user.users_interested.values_list('id', flat=True))

    #pass set to template
    return render(request, "base.html", {'publications': publications, 'user_publication_set': user_publication_set})

base.html

{% for publication in publications %}

  {{publication.title}}

  {% if publication.id in user_publication_set %}
      i am already interested
  {% endif %}

{% endfor %}

Found this solution in Django: check for value in ManyToMany field in template

2
wencakisa On

Try like this:

{% if request.user in publication.users_interested.all %}
  • request.user property holds the current logged in user
  • Then you use the in operator with publications.users_interested.all() (Note that there are no parenthesis on .all() in template