I have set up a few models as follows:
Page
Gallery
Image
Gallery and Image share a many to many relationship.
Page can have 1 or 0 galleries.
I have created a gallery with a few images and attached it to a page object.
However, I’m having trouble displaying it in a template.
Can anyone help?
My page view looks like this:
def detail(request, page_id):
p = get_object_or_404(Page, pk=page_id)
return render_to_response('page/detail.html', {'page': p},
context_instance=RequestContext(request))
And the template:
{% block images %}
{% if page.gallery %}
{% for image in page.gallery.image_set.all %}
<a rel="gallery" href="{{ STATIC_URL }}{{ image.image }}"></a>
{% endfor %}
{% endif %}
{% endblock %}`
If I try to output some text within the IF block it comes out OK but not within the loop.
Any advice on getting it to work / generally tidying this up would be greatly appreciated.
Thanks.
If the
Gallery-Imagerelationship is many to many I’m guessing you have anm2mfield on yourGallerymodel, where the m2m manager is the field itself. The manager can be queried just like any otherQuerySet:model_instance.mym2mfield.filter().If your
ManyToManyFieldis calledimageson theGallerymodel, your template would look like this:If your
ManyToManyFieldis on yourImagemodel, the default name would be as you describe, unless you specified arelated_namein which case you’d use that name.