Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load static file with variable name in django

I'm trying to do load the following static file

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

where image is in a for loop of images derived from a database.

But I simply got an error Could not parse the remainder: '{{' from ''static/matrices/'{{'

What should I do to fix this? I can't use relative paths because this will be used by subsections as well, with the same html template.

like image 218
user2649814 Avatar asked Aug 04 '13 07:08

user2649814


People also ask

How does Django load static files?

Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.

How does Django handle static and media files?

Static Files in ProductionUse a web server like Nginx to route traffic destined for your static files directly to the static root (configured via STATIC_ROOT ) Use WhiteNoise to serve up static files directly from the WSGI or ASGI web application server.

What does {% load static %} do in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.


2 Answers

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.

like image 165
dalore Avatar answered Sep 19 '22 16:09

dalore


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>
like image 39
rounin Avatar answered Sep 22 '22 16:09

rounin