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

Time:01-09

Trying to display an image on a webpage with django templates

{% for article in article_roll %}
    <li><div  id="blog{{ forloop.counter }}">
        {% load static %}
        <img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
        <div >
            <span >{{ article.image }} {{ article.title }}</span>
            <span >{{ article.date }}</span>
        </div>
        <span >{{ 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.

the static url comes out as

<img src="/static/{{ article.image }}" 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.

CodePudding user response:

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

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