It seems it is not possible to loop over a RelatedManager in a
template.
I have two models, Author and Article, joined by the relevant foreign
key.
For each author, I want to display the list of his articles
If I do, for each author :
{% for article in author.article_set %}
{{article.title }}
{% endfor %}
I get a TypeError, 'RelatedManager' object is not iterable
If I do this :
{% for article in author.article_set.all %}
{{article.title }}
{% endfor %}
I don't get any errors, but no output either.
Did I miss something ? Or do I have to write a get_articles method in
the Author model, which the template will know how to handle ?
Cheers,
Olivier
> {% for article in author.article_set.all %}
> {{article.title }}
> {% endfor %}
works fine.
Olivier
It certainly is possible.
> If I do this :
> {% for article in author.article_set.all %}
> {{article.title }}
> {% endfor %}
This looks like the correct syntax. There are a limited number of
things that could be going wrong. Either:
- The author object being provided in the context doesn't have any articles
- The article doesn't have a 'title' attribute
- The value of article.title is '' for every article
- There is a typo in your template that you haven't made in this email.
Some debugging hints:
- Try putting TEMPLATE_DEBUG_IF_INVALID='INVALID' in your settings
file. This will put some INVALID text into your generated output
whenever a template variable can't be expanded
- Try putting some other content inside the loop (some dummy text) -
This will determine if the loop is occurring.
> I don't get any errors, but no output either.
Not getting errors isn't surprising; the template language generally
fails silently, to prevent the end user seeing things they shouldnt.
Hence the TEMPLATE_DEBUG_IF_INVALID setting for debug purposes.
> Did I miss something ? Or do I have to write a get_articles method in
> the Author model, which the template will know how to handle ?
No. The object instance can provide sufficient detail to the template
to render related objects.
Yours,
Russ Magee %-)
Yes, one of those occured, I noticed too late....
Thank you for you very detailed answer.
Olivier