[Django]-How to add django template variable in <img src>?

3πŸ‘

βœ…

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.

2πŸ‘

Do it like this:

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

Use it after the static tag scope ends.

1πŸ‘

Uses a for tag

{% for p in photos %}
    <img src="{% static '{{ p.path }}' %}"/>
{% endfor %}

Better uses Imagefield as field in your model

In your settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Create a folder named β€œmedia” in your project (at the same level that your apps)

In your urls.py (main)

from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns


urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In your models.py

Replace the CharField with Imagefield

image = models.ImageField(upload_to="my_folder_name")

Like this:

class Photo(models.Model):
    title = models.CharField()
    image = models.ImageField(upload_to="my_folder_name"))

In your views.py

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

In your templates

{% for p in photos %}
    <img src="{{ p.photo.url }}"/>
{% endfor %}

0πŸ‘

For Template

{% for image in all_image %}
    <img src="{{ image.image.url }}"/>
{% endfor %}

0πŸ‘

Solved: load image dynamically in survey.html

"survey.toolsTechnology" is a dynamic variable, every time the
variable changes, the image also changes based on it.

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

Leave a comment