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?
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 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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With