views:

46

answers:

2

Hello. I have a Django model with a ManyToManyField and I'm trying to iterate the contents of that field in a comma-delimited list in my template. I'm getting some unexpected results.

{% for painting in paintings_list %}
    <p>{% for item in painting.style.all %}
        {{ item.style|join:', ' }}
    {% endfor %}</p>
{% endfor %}

The contents are being displayed as they exist in the database, but they're displayed in an unanticipated way...ie. instead of:

Renaissance, Baroque, Expressionist

I'm getting:

R,e,n,a,i,s,s,a,n,c,e,,B,a,r,o,q,u,e,,E,x,p,r,e,s,s,i,o,n,i,s,t

Any idea what I'm doing wrong? Would have thought the join template filter was for exactly this type of scenario, but perhaps the proper way to do this would be to create a custom method of the model...

A: 

item.style is returning a string, so you're joining each character with , instead of each item.

Ignacio Vazquez-Abrams
+1  A: 

Ignacio Vasquez-Abrams is correct (as usual). A solution to your problem might lie in the forloop variables.

<p>{% for item in painting.style.all %}
  {{item.style}} {% if not forloop.last %}, {% endif %}
{% endfor %}</p>
czarchaic
Link to documentation: http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#for
Felix Kling