Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Syntax for using {{ article.image }} inside {% static %} with django templates

Trying to display an image on a webpage with django templates

{% for article in article_roll %}
    <li><div class="blog-post" id="blog{{ forloop.counter }}">
        {% load static %}
        <img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
        <div class="blog-post-preview">
            <span class="blog-title">{{ article.image }} {{ article.title }}</span>
            <span class="blog-date">{{ article.date }}</span>
        </div>
        <span class="blog-text">{{ article.preview }}</span>
    </div></li>
{% endfor %}

This is the part that’s giving me trouble

<img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">

{{ article.image }} is an ImageField in an SQLite Database setup with the default configurations django has. My main concern is loading up the correct image for each article as the for loop progresses, but I can’t even get {{ article.image }} to evaluate to anything useful within the {% static %} braces.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the static url comes out as

<img src="/static/%7B%7B%20article.image%20%7D%7D" alt="image thing">

When what I’m trying to get is

<img src="/static/value_of_{{article.image}}" alt="image thing">

I’ve tried escaping characters, avoiding using ‘ ‘, and rewriting the urls.

I feel like I might be approaching this problem entirely wrong and there’s a better way to do it, but I’ve been looking through the documentation and haven’t seen anything obvious to me.

>Solution :

You don’t need the '{{ }}' inside the static tag.

<img src="{% static article.image %}" alt="{{ article.alt }}">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading