Django: show a ManyToManyField in a template?

后端 未结 3 1823
别跟我提以往
别跟我提以往 2020-12-01 01:23

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         


        
相关标签:
3条回答
  • 2020-12-01 02:00

    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 %}
    
    0 讨论(0)
  • 2020-12-01 02:04

    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 %}
    
    0 讨论(0)
  • 2020-12-01 02:05

    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 %}
    
    0 讨论(0)
提交回复
热议问题