Reputation: 437
I have a normal app that has a directory structure similar to the following:
...static/
Training/
css/
img/
js/
...templates/
....
Within one of my templates, I would like to get the image name from the database and build the path to the image. For example, if I had the image MyPicture.jpg, then I would like to include static and combine this with 'Training/img/' and the file name to get something like
'..path to static../Training/img/MyPicture.jpg'
I found the following article that suggested using template tags, so I have tried this:
from django import template
register = template.Library()
@register.filter
def addstr(arg1, arg2):
# Apparently, add has side effects, so use this:
# https://stackoverflow.com/questions/4386168/how-to-concatenate-strings-in-django-templates
return str(arg1) + str(arg2)
With the template:
{% with static|addstr:"Training/img/"|addstr:course.img as imgpath %}
<img class="card-img rounded-lg rounded-top" src="{{ imgpath }}" alt="Card image">
{% endwith %}
This is unfortunately leaving out the static part of the address.
How do I combine all three parts ?
[p.s. I have a {% load static %} at the top of the template ]
Thanks
Mark
Upvotes: 0
Views: 263
Reputation: 437
Silly mistake really. All I needed to do was separate out the static and not treat it like a string. This works:
"{% static 'Training/img/'|addstr:course.img %}"
Upvotes: 0
Reputation: 379
if you wanna show the absolute full url, this is what you need:
{{request.scheme}}://{{request.META.HTTP_HOST}}{{object.filefield.url}}
but if you just need to show the file, you can use this:
<img class="card-img rounded-lg rounded-top" src="{{ object.filefield.url }}" alt="Card image">
Upvotes: 1