Home > Back-end >  Django: Accessing full User information via ManyToMany field
Django: Accessing full User information via ManyToMany field

Time:06-19

everyone- I'm new to Django and working on my first big project and I'm having trouble with accessing default Django User model information via a ManyToMany relationship. I've spent a great deal of time searching and can't crack it.

models.py

class Event(models.Model):
  event_name = models.CharField(max_length=200, null=True, unique=True)
  #etc...

class School(models.Model):
  user = models.ManyToManyField(User)
  event = models.ForeignKey(Event, null=True, on_delete=models.PROTECT)
  #etc...

My url contains the id of the Event, so...

views.py

def schools(request, pk):
   event = Event.objects.get(id=pk)
   school = School.objects.filter(event=event)
   return render(request, 'accounts/schools.html', {'event':event, 'school':school})

template

{% for school in school %}
   <tr>
      <td>{{school.name}}</td>
      <td>{{school.user.all}}</td>
{% endfor %}

On my template, I'm able to use {{school.user.all}} to get me a Queryset displayed with the username of each User, but I want the first_name and last_name and can't see to figure out how to get that..

Thank you for any suggestions. I greatly appreciate your time!

CodePudding user response:

I was able to add this to my school model to get what I wanted:

    def director(self):
        test = ",".join([str(p) for p in self.user.all()])
        user = User.objects.get(username=test)
        return user.first_name   " "   user.last_name

HOWEVER: if there is more than one user associated with "School" it displays blank

CodePudding user response:

You should include users to your context.

I'll explain how you can display users of a single school below in a ManyToMany relationship, as it is the main point of your question. I think you can do the rest if you want to display all users of all schools in the same page.

In view function:

school = School.objects.get(pk=1)
users = school.user.all()

Last line of view function:

return render(request, 'school_users.html', {'users': users})

And in your template:

{% for user in users %}
  <tr>
  <td>{{ user.first_name }}</td>
  <td>{{ user.last_name }}</td>
  </tr>
{% endfor %}

You didn't include your User model, so I assumed that it has first_name and last_name attributes.

  • Related