Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add django template variable in <img src>?

I have a Photo model with two fields:

title = models.CharField()
path = models.CharField()

When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:

def gallery(request):
   photos = Photo.objects.all()
   return render(request, 'gallery.html', {'photos': photos})

This is the tag in gallery.html:

{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>

The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:

src="static/%7B%7B%20photo.path%20%7D%7D"

What is the problem? How can I use template variables in src? P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like

<img src="{static 'images/image_ex.png'%}">

The photo renders normally.

like image 897
varham Avatar asked Oct 22 '25 14:10

varham


2 Answers

You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.

If you want to use the content of photo.path, you can use:

<img src="{% static photo.path %}"/>

So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.

like image 166
Willem Van Onsem Avatar answered Oct 24 '25 04:10

Willem Van Onsem


Do it like this:

<img src="{%static 'images/'%}{{image_ex.png}}">

Use it after the static tag scope ends.

like image 41
Tushar_noob Avatar answered Oct 24 '25 05:10

Tushar_noob