Templates for foreign users and Django

So here is the problem. Imagine 2 models: photographer and photo. The strict rule is that there can be only 1 photographer for an image, so Photo has a ForeignKey link to Photographer.

class Photographer(models.Model): name = models.CharField(max_length = 40) class Photo(models.Model): name = models.CharField(max_length = 40) photographer = models.ForeignKey(Photographer) 

Now I would like to show the most famous photographers on the main page with 3 of his most popular photographs. Therefore, it should be something like:

 # views.py def main(request): photographers = ... return render_to_response("main_page.html", { "photographers": photographers }) #main_page.html {% for photo in photographers.photo_set.all()[:3] %} {{ photo.name }} {% endfor %} 

But the Django template system does not allow all () and [: 3]. So what is the best way to do this? The most obvious solution would be to create objects on the fly (creating an array of photographers and photographs and transferring it to a template), but I just don't see a good way to do this.

Please do not just refer me to the Django manual, I read it completely, but could not find the answer ...

+4
source share
3 answers

Try using the cut filter :

 {% for photo in photographers.photo_set.all|slice:":3" %} 

Note that .all does not need to be explicitly called.

+6
source

I think Yuval almost got it, but not quite - the photographs and photographers seem to have been involved. I think the best approach is to provide the top_photos attribute in the Photographer model, which returns the 3rd (or as many as you like) photos. Then:

  {% for photographer in photographers%}
 Photographer: {% photographer.name%}
 Top photos:
 {% for photo in photographer.top_photos%}
 {% photo.name}
 {% endfor%}
 {% endfor%}

I forgot the HTML formatting above, but hopefully the intention is clear.

+2
source

You got it, you just need to move the logic to the view and just pass the template to the objects when you get them.

 # views.py def main(request): photographers = photographers.photo_set.all()[:3] return render_to_response("main_page.html", { "photographers": photographers }) #main_page.html {% for photo in photographers %} {{ photo.name }} {% endfor %} 

Make sure your views contain logic, and the template just shows the data.

+1
source

All Articles