1

I am trying to render a ManyToManyField from a model that render a list of hotels with staff that belong to each hotel.

I am trying to display in the template the users that are inside the current hotel being shown but I get an error

auth.User.None

my template

{% for Hotel in object_list %}
         {{ Hotel.collaborateurs }}
              {% endfor %}

My models.py

class Hotel(models.Model):
collaborateurs = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés")
              (....)

Thanks

Edit ;

I am able to rend users but I have an unesthetic code being render : .

I would like to render only the username.

3 Answers3

2

You need to use .all as manytomany relations are always lazy loaded in django.

Hotel.collaborateurs.all

Moreover variable names should be lowercase in Python.

collaborateurs = need an indent on the left side.

Hope that helps.

Tobias Ernst
  • 4,214
  • 1
  • 32
  • 30
0

models.py

class Song(models.Model):
user = models.ManyToManyField(User)
song_name = models.CharField(max_length=50)
song_duration = models.IntegerField()

def written_by(self):
    return ",".join([str(p) for p in self.user.all()])

html file

    {% for data in data %}

        {{data.written_by}}   # It returns username
        {{data.song_name}}
        {{data.song_duration}}

    {% endfor %}
0

You can use

{{ Hotel.collaborateurs.all.count }}

and that will provide the total number.

Awire360
  • 11
  • 3