load static file with variable name in django - python

I'm trying to do load the following static file
img file
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.

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 %}
img file
or
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
img file
Reference: get_static_prefix

You should avoid nesting tags.
What are you trying to solve? Isn't the image part of dynamic content? The static tag is for static content not uploaded media files.
If you must use the static tag the correct way would be something in the order of;
{% static image %} or {% static image.file %}
Depending on the object layout. If you're using an ImageField (inherits FileField) the image object already holds the path, so there's no need to manually add extensions.

What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.
I didn´t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-" %}
{{ option.name.lower }}-selected.png">
{% endfor %}
EDIT:
Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-"
|add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}

Too many quotes!
Just
img file
and you don't have to call the static in the link because you already load the static

Related

How to passing queryset inside static url in django template?

So, I have image in static folder, with the name of image same with username field that I have created. I want to show the photo for every posting based on the post that made by that user. I just thinking to pass the queryset inside static url like this:
{% for post in data %}
<img src="{% static 'project/image/{{ post.username }}.jpg' %}" alt="Profile" id="profile_image">
{% endfor %}
But my image don't want to show up (error), and the terminal looks like this:
[27/Feb/2021 15:43:14] "GET /static/project/image/%7B%7B%20post.username%20%7D%7D.jpg HTTP/1.1" 404 1758
Is there any way to do this?
If you want to use the curly brackets, then you need to hard code the whole path of the image.
static/project/image/{{ post.username }}.jpg
It uses {{ post.username }} as text, and then percentage encodes it. In order to interpret it, just remove the curly brackets and work with the |add: template filter [Django-doc]:
{% with post.username|add:".png" as username %}
<img src="{% static 'project/image/'|add:username %}" alt="Profile" id="profile_image">
{% endwith %}
For example:
>>> Template('{% load static %}{% with post.username|add:".png" as username %}{% static "project/image/"|add:username %}{% endwith %}').render(Context({'post': {'username': 'foo'}}))
'/static/project/image/foo.png'
That being said, this is quite complicated. If you work with a FileField [Django-doc], then you can convert this to media URLs, and render this with {{ myobject.myfilefield.url }}.

Django: Is there a way to use static with default_if_none?

In my Django template I'm using static to pull images from the static/ folder based on each item's (byte) id property. An example of a path to an image would be: static/images/promo-abc.png I'm building the path to the image using with:
{% for byte in bytes %}
{% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %}
<img class="promo-image" src="{% static image_static %}"/>
{% endwith %}
However if there is no image based on the item's id I'd like the 'default' image to be used: static/images/promo-dummy.png. For that I'm trying to use default_if_none but so far this isn't working (getting error: Could not parse some characters:...)
{% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %}
<img class="promo-image" src="{{% static image_static |default_if_none:'images/promo-dummy.png' %}}"/>
{% endwith %}

How to use autoescape off AND static variables inside django template

I'm using auto generated HTML which has been saved to a file and then read in again to use as part of a page in a django template.
In order to do this I have used:
{% autoescape off %}
{{ my_html }}
{% endautoescape %}
However, in the my_html variable, I have some static content. This comes in the form of something like this:
<img src="{% static "img/tree_report.png" %}" width="12px" height="12px"/>
My issue is that the static content is not displayed. I get:
http://127.0.0.1:8000/%7B%%20static 404 (in the browser error report)
I read something about get_static_prefix in another question but that doesn't solve my problem because I just get this instead:
GET http://127.0.0.1:8000/%7B%%20get_static_prefix%20%%7Dimg/tree_report.png 404 (Not Found)
I also tried endautoscape turning on and off periodically in my_html in the saved HTML variable. That also didn't work.
Should I be autogenerating the development and production static files paths for my_html or is there a more elegant solution to this problem?
Any suggestions are most welcome.
Thanks.

What's the difference between template include and static include in Django?

I'm trying to learn Django at the moment and am trying to make sure I'm not doing anything stupid.
I'm in the process of making my web page more modular in the sense that I am removing hardcoded values in the template (base .html). Doing so, I'm trying to convert hardcoded CDN references (jquery, bootstrap, etc.) to modular pieces that can be included in every web page. Doing so will allow me to change a single file in the future, instead of being forced to go to every web page and make that change.
However, I'm slightly confused. I'm trying to determine if it would make sense to copy them into a html file and use Django's {% include '' %} template tag to directly include the cdn portions, or if using Django's static include would be more appropriate.
So what exactly is the best route? It seems like it would be very easy to use template includes for everything static in all honesty. Why not use it to include javascript or css?
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”.
We call them 'static' simply because they aren't dynamic i.e the contents of these files are relatively fixed, either by design or by it's intrinsic characteristics (eg: binary content like images) and thus does not need to processed by our application server.
We differentiate them from other files because it's advisable to serve these static files at a lower level, for example, using nginx. This allows us to serve these files faster as is which leads to performance gains. It also allows easy caching.
But when using a CDN, you offload this work from your server to somebody else's server.
Now coming back to your question. You shouldn't have to declare your resources in every template. Usually, base.html contains the base of the page which can then me extended (read: template inheritance) by more specific (children) templates.
To understand this quickly, here's an example:
base.html:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="~~CDN HERE~~">
<script src="~~CDN HERE~~"></script>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
article.html
{% extends "app/base.html" %}
{% load static %}
{% block body %}
<h1>{{ page_title }}</h1>
<img src="{% static 'app/img/detective.png' %}" alt="detective" />
{{ page_content | safe }}
{% endblock %}
Now for every article on your site, you render the article template which automatically extends the base removing the need to mention your css/js files for multiple pages.
If you're using different resource files for different pages, you can creation an additional block like {% block css %}{% endblock %}
and then add this to your article.html
{% block css %}
<link rel="stylesheet" href="{% static 'app/css/article.css' %}">
{% endblock %}
Notice how I'm using static for image, which is served directly by nginx.
Theoretically, you can club your CDN links into a file and then include it in base.html, but it just leads over modularity which causes redundant complexity.
Let me know if you have any issues!

Django Server Static files

I am trying to use the following code to link to the correct image based on the rating. However the server interprets as http://127.0.0.1:8000/static/images/rating-%7B%7Bfeedback.reception_courtesy%7D%7D.gif instead of http://127.0.0.1:8000/static/images/rating-1.gif
<img src="{% static 'images/rating-{{feedback.reception_courtesy}}.gif' %}" alt="My image"/>
I am not sure where I am running wrong here.
The problem is that variables are not interpolated within the url parameter of {% static 'url' %}, so {{feedback.reception_courtesy}} is taken literally.
Do it like this:
<img src="{% static 'images' %}/rating-{{feedback.reception_courtesy}}.gif" alt="My image"/>
This works fine because the variable is now outside of {% static ... %}, and because {% static 'one/two/three' %} is equivalent to {% static 'one/two' %}/three

Categories

Resources