Reputation: 2177
I have a list of photos from which I would like to always be the first to add as a profile photo. I found the following '|first' tag in the django documentation, but I have problems to add it in my situation, every time I try to do it in this way, '{{ image_list|first.photo.url }}' i receives nothing.
Any help will be appreciated.
My models.py
class Image(models.Model):
photo = models.ImageField()
added_at = models.DateTimeField(auto_now_add=True)
masseurs = models.ForeignKey(Masseurs, on_delete=models.CASCADE)
views.py
masseur = get_object_or_404(Masseurs, pk=masseurs_id)
image_list = Image.objects.filter(masseurs_id = masseurs_id)
return render(request, 'masseur/masseur_detail.html', {'image_list':image_list})
Upvotes: 1
Views: 201
Reputation: 5289
Since image_list
is a QuerySet and not a list, |first
won't work. You can however use:
{{ image_list.first.photo.url }}
For reference, see : Accessing Method Calls
Most method calls attached to objects are also available from within templates. This means that templates have access to much more than just class attributes (like field names) and variables passed in from views.
Upvotes: 1
Reputation: 3286
Why don't you do it in the view?
image = Image.objects.filter(masseurs_id=masseurs_id).first()
But if you need to do it in the template:
{{ image_list.first.photo.url }}
This is because image_list
is a queryset, so you can get the first item of the queryset with the .first() syntax
Upvotes: 1