Views / Template - displaying data from other class.

3 views
Skip to first unread message

Petey

unread,
Aug 2, 2011, 12:14:06 PM8/2/11
to django...@googlegroups.com
Hi.

I want to display images for news. Images class is a seperate model.

In generic view (index) to display news and images I use 2 "for" loops which work.

In "single" view I use get_object_or_404 which changes a bit the template - it does not require the loops to display the text.
If I understand it correctly I can't import data from other models for certain model without proper loop?

How shoud I modify the "single" view and "single" template to make it display images from images class?

http://pastebin.com/k6uzUktq

bruno desthuilliers

unread,
Aug 2, 2011, 1:57:39 PM8/2/11
to Django users
First rename your "image_fk" field in Image to "news" - it's a
relation from an image to a news, not from an image to another image,
and the "_fk" prefix is irrelevant.

Then, from a News instance, you'll be ables to access the related
images using younews.image_set.all in the templates, ie:


{% for news in object_list %}
# display the news stuff here
{% for image in news.image_set.all %}
# display the image here
{% endfor %}
{% endfor %}

Just skip the outer loop for the "single" template.

FWIW, all this is documented, and IIRC there are examples in the
tutorial.

Reply all
Reply to author
Forward
0 new messages