Reputation: 3429
I am preparing a image gallery for my website using Django
. I have basically a Gallery Model Foreign Key
in my Image Model
. I have a BooleanField
in my Image
model to make a cover photo.
What I need is to get True value for the one in between images.
{% for gallery in gallery_list %}
<div class="grid-item {{ choices | random }}">
<a href="#" data-background="{{gallery.images}}#howtofilter?#" data-rel="lightcase:gal" title="Image Caption"></a>
</div>
{% endfor %}
I checked the documents for custom filters trying to solve but I could not figure out. Can you help me ?
Thanks
Ps Edit: adding my models
class Gallery(models.Model):
title = models.CharField(max_length=200,verbose_name=_("gallery_title"),help_text _("Enter the Gallery title"))
class Image(models.Model):
title = models.CharField(max_length=200,verbose_name=_("image_title"),help_text _("Enter the Image title"))
gallery = models.ManyToManyField(Gallery)
is_cover_photo = models.BooleanField()
Upvotes: 1
Views: 443
Reputation: 299
It's good to keep complex logic like this outside of your templates to avoid them getting too complicated. Save it for the views and/or models!
Sounds like the best bet here would be to have a method on your Gallery
model to get the Image
that has the cover image. Something like:
class Gallery
...model fields...
def get_cover_image(self):
return self.images_set.filter(cover_photo=True).first()
Then in your template, assuming the Image
model has a property like url
:
{% for gallery in gallery_list %}
<div class="grid-item {{ choices | random }}">
<a href="#" data-background="{{gallery.get_cover_image.url}}" data-rel="lightcase:gal" title="Image Caption"></a>
</div>
{% endfor %}
To save lots of DB queries here you might need/want to use prefetch_related
to get all the Image
objects you'll need to display the galleries, but that's a different question.
Upvotes: 1
Reputation: 39659
You could write a method in Gallery
model to return you a cover image:
class Gallery(models.Model):
# other fields
def cover_image(self):
return self.image_set.filter(is_cover_photo=True).first()
Then in template:
{% for gallery in gallery_list %}
{% with cover=gallery.cover_image %}
{% if cover %}
{# do something with cover image #}
{% endif %}
{% endwith %}
{% endfor %}
Upvotes: 1