I am trying to display a list of objects (images) based on a many-to-many relationship (image / gallery using the Galleryimage model).
Galleryimage has an additional field called the position that I want to use to control the order in which images are displayed in the template.
I also have a page model, which, if necessary, can have a gallery attached to it.
My models look like this:
class Page(models.Model):
gallery = models.ForeignKey(Gallery, blank=True, null=True)
slug = models.SlugField()
title = models.CharField(max_length=200)
content = models.TextField()
def __unicode__(self):
return self.title
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images')
def __unicode__(self):
return self.title
class Gallery(models.Model):
title = models.CharField(max_length=50)
images = models.ManyToManyField(Image, through='Galleryimage')
def __unicode__(self):
return self.title
class Galleryimage(models.Model):
image = models.ForeignKey(Image)
gallery = models.ForeignKey(Gallery)
position = models.IntegerField()
class Meta:
ordering = ['position']
I retrieve the page model in my view as follows:
def detail(request, page_id):
p = get_object_or_404(Page, pk=page_id)
return render_to_response('detail.html', {'page': p},
context_instance=RequestContext(request))
And finally, I show the images in the template like this:
{% block images %}
{% if page.gallery %}
{% for image in page.gallery.images.all %}
<a rel="gallery" href="{{ STATIC_URL }}{{ image.image }}"></a>
{% endfor %}
{% endif %}
{% endblock %}
Images are all displayed as expected, the order always seems the same no matter what I do.
Can anyone give me a push in the right direction?
Any advice is appreciated.
Thank.