user585936
user585936

Reputation:

Make a change to a string in django template?

I have a queryset in Django that contains a string field. This is a filename, something like images/photo.jpg or images/photo.20.19.22.jpg. I need to rewrite them in one particular view so that ".thumbnail" is inserted before the extension. The previous names should become images/photo.thumbnail.jpg and images/photo.20.19.22.thumbnail.jpg.

What is the best way to do this? This is part of a queryset so it will look like:

{% for record in list %}
  {{ record.image }}
{% endfor %}

Now of course I would love to do this outside of my template. However, I don't see a way in which I can do that. After all, this needs to be done for every record inside my queryset. To complicate things, this record does not come directly from a modal. This record is coming from a subquery, so I don't see a way for me to change the modal itself. Should I use templatetags for this? Any other recommendations?

FYI the subquery is something like this:

>>> from django.db.models import OuterRef, Subquery
>>> newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
>>> Post.objects.annotate(image=Subquery(newest.values('image')[:1]))

Upvotes: 0

Views: 155

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

A simple custom template filter could do this.

@register.filter
def add_thumbnail(image):
    return image.replace('.jpg', 'thumbnail.jpg')

And in the template:

{% for record in list %}
  {{ record.image|add_thumbnail }}
{% endfor %}

Upvotes: 2

Related Questions