0

I'm trying to load an image whose url is composed of a vairable numerical value. Is there a template only solution to this or do I really have to create a filter in extras.py? I would rather just write this one liner. Something along the following lines:

{% with urltemp="media/"|add:info.personid|stringformat:"s"|add:".jpg"  %}
        <img src="{% static urltemp %}" onerror="this.style.display='none'"/>
{% endwith %}
1

3 Answers 3

1

I know you can use {% static your_url %} but I allways prefer to do like this:

I have my images in myproject/static/img/

My {{STATIC_URL}} (settings.py variable) points to myproject/static

So in a template I usually do: <img src="{{STATIC_URL}}img/image_name.png" />

Or using an ImageField

{% for item in item_list%}
    <img src="{{ item.image.url }}" />
{% endfor %}

In your case you could do:

<img src="{{ MEDIA_URL }}{{ info.personid }}.jpg" />

{{ MEDIA_URL }} already ends with /

  • You need MEDIA_URL to be defined in your settings.py
Sign up to request clarification or add additional context in comments.

Comments

0

How about:

<img src="{% get_media_prefix %}{{ info.personid }}.jpg"/>

Comments

0

Try this

        {% for name in image_list %}
          <div>
            <img src="{% static %}string_path/{{name.image}}.jpg" alt="img">
          </div>
        {% endfor %}

1 Comment

static needs at least one argument. This won't work (at least in Django >= 4.2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.