load static file with variable name in django load static file with variable name in django django django

load static file with variable name in django


You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.

{% load staticfiles %}{% with 'images/'|add:image.title|add:'.png' as image_static %}  {% static image_static %}{% endwith %}

But in your use case it might be better if you just store the path of the images on the image model itself.


I got this to work by using an empty string for the static path and then using my variables in their own section, like this:

<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>


You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:

{% load static %}<a href="{% get_static_prefix %}static/images/{{ image.title }}.png">img file</a>

or

{% load static %}{% get_static_prefix as STATIC_PREFIX %}<a href="{{ STATIC_PREFIX }}static/images/{{ image.title }}.png">img file</a>

Reference: get_static_prefix