0

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

2 Answers 2

1

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"> 
Sign up to request clarification or add additional context in comments.

1 Comment

object.filefield.url just make the src blank. The object that I am using is from the database, not the actual file. My problem is generating a string that points to a certain directory. I could do this outside of the template, but I don't understand why I cannot concatenate static, 'Training/img/' and a filename within the template. Thanks
0

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 %}" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.