F
F
Fedor_PV2018-07-19 07:41:16
Django
Fedor_PV, 2018-07-19 07:41:16

How to insert variable into file path in Django template?

Dear Django pros, my lack of experience leads me to ask for help with the following question: I
have a project that has a 'countries' application in which each user enters certain data. The PYGAL module, depending on the entered data, builds an image that is loaded in the template as:

{% load static %} 

<img src="{% static 'countries/World.svg' %}" >

'countries/World.cvg' is the path. The picture created by pygal is called World.svg, and it is in the static/countries/ folder.
Here is the question - the view function processed the data entered by the user, passed it to PYGAL, it draws for each user its unique picture. And, accordingly, the Django template should read {{ user }} and display exactly its unique picture from many others.
For each individual user, the template should load different pictures. How to implement it? After all, I have to specify the path to the picture in the template, including its name. I can force PYGAL to save images with a different name for each user, but how do I make the template understand that for a particular {{ user }}, it is his image that needs to be loaded? How to insert a variable image name (depending on the user) in the tag ?
<img src="{% static 'countries/World.svg' %}" >

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Kopitsa, 2018-07-19
@Fedor_PV

The static tag accepts a string or a variable.
If the variable is not in the context:

{% with var1='user/123.svg' %}
<img src="{% static var1 %}">
{% endwith %}

if there is - then just {% static varname %}
PS I would take out the logic for choosing a picture from the template to the view or by a method to the user model

M
Muromati, 2020-01-31
@muromati

<img src="{% static 'countries/'|add:YOUR_VAR|:add:'.svg' %}">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question