Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: show a ManyToManyField in a template?

Tags:

django

I've got these models in my Django project:

class Area(models.Model):     name = models.CharField(max_length=100, primary_key=True)     def __unicode__(self):         return self.name class Place(models.Model):     id = models.IntegerField(primary_key=True)      name = models.CharField(max_length=100, primary_key=True)     area = models.ManyToManyField(Area,related_name='area') 

How can I show the Place's area name(s) in my template? Currently I have:

{% for place in places %}     Name: {{ place.name }}, Area: {{ place.area}} {% endfor %} 

which gives:

Area: <django.db.models.fields.related.ManyRelatedManager object at 0x10435a3d0> 

And {{ place.area}} is just blank. Can anyone help?

like image 312
AP257 Avatar asked Nov 24 '10 18:11

AP257


People also ask

How do you pass variables from Django view to a template?

How do you pass a Python variable to a template? And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

What {{ name }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


1 Answers

Use place.area.all in the template
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

{% for place in places %}     Name: {{ place.name }}<br/>     Area: <br/>{% for area in place.area.all %}{{ area }}<br/>{% endfor %} {% endfor %} 
like image 192
crodjer Avatar answered Nov 13 '22 15:11

crodjer