Reputation: 37
I have a couple of classes in a model linked with ManyToManyField:
class UserProfile(models.Model):
contacts = models.ManyToManyField(Contact)
class Contact(models.Model):
first_name = models.CharField(max_length=50)
In a view I am passing:
contacts_list = request.user_profile.contacts
This produces some strange string of numbers that changes each time the template is refreshed:
{% for c in contacts_list %}
{{ c }}
{% endfor %}
This produces nothing:
{% for c in contacts_list %}
{{ c.first_name }}
{% endfor %}
In my Contact class I also have the __unicode__(self)
defined to return the first_name
, so why does the ManyToManyField
object not return this value? I also cannot figure out how to successfully display the first_name
field values. Thanks for any suggestions or help!
Upvotes: 2
Views: 1200
Reputation: 31633
Try adding all
to view:
contacts_list = request.user_profile.contacts.all()
or to template:
{% for c in contacts_list.all %}
{{ c.first_name }}
{% endfor %}
Upvotes: 4