137👍
✅
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 %}
34👍
You can use the existing join template tag.
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#join
Here’s the code
{% for place in places %}
Name: {{ place.name }}, Area: {{ place.area.all|join:", " }}
{% endfor %}
- [Django]-TemplateDoesNotExist – Django Error
- [Django]-Using {% url ??? %} in django templates
- [Django]-Django "login() takes exactly 1 argument (2 given)" error
9👍
What does your view code look like?
Here’s one way you can return the related models:
from myapp.models import Area, Place
def detail(request, place_id):
place = Place.objects.get(pk=place_id)
areas = place.area.all()
return render_to_response('detail.html', {
"place": place,
"areas": areas,
})
This example is just for illustration; you’d want to include error-handling code.
Your template might look something like this:
<h3>{{ place }}</h3>
{% if areas %}
<ul>
{% for area in areas %}
<li>{{ area.name }}</li>
{% endfor %}
</ul>
{% endif %}
- [Django]-Django Admin: Using a custom widget for only one model field
- [Django]-Redirect / return to same (previous) page in Django?
- [Django]-Homepage login form Django
5👍
For show only ManyToMany field:
{% for place in places.area.all %}
{{ place.name }}
{% endfor %}
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Fighting client-side caching in Django
- [Django]-Nginx doesn't serve static
Source:stackexchange.com