Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django for loop counter break

This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.

The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't think is possible is something like (pseudocode):

{% for photos in gallery.photo_set %}    {% if forloop.counter lt 3 %}      <img src="{{ photos.url }}">    {% endif %} {% endfor %} 

Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field.

Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.

like image 266
f4nt Avatar asked Jun 14 '09 05:06

f4nt


People also ask

How do I stop a loop in Django?

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


2 Answers

Use:

{% for photos in gallery.photo_set|slice:":3" %} 
like image 95
Alex Martelli Avatar answered Oct 17 '22 01:10

Alex Martelli


This is better done in the gallery.photo_set collection. The hard-coded "3" in the template is a bad idea in the long run.

class Gallery( object ):    def photo_subset( self ):        return Photo.objects.filter( gallery_id = self.id )[:3] 

In your view function, you can do things like pick 3 random photos, or the 3 most recent photos.

   def photo_recent( self ):        return Photo.objects.filter( gallery_id = self.id ).orderby( someDate )[:3]     def photo_random( self ):        pix = Photo.objects.filter( gallery_id = self.id ).all()        random.shuffle(pix)        return pix[:3] 
like image 30
S.Lott Avatar answered Oct 17 '22 02:10

S.Lott