3

I've got a Python function in my Django project where I need to return some HTML code, including the static URL where my images reside.

In a template, I can do <img src="{% static 'img/my_img.png' %}">. Any idea how I can get this in Python code as part of a return statement?

Obviously I could include the whole URL in my return statement (as per the below) but this would violate Django's DRY principle (and would be problematic in case my image URL would change).

if my.condition:
    return "<img src='/img/my_img.png' />" + obj.name

Using Django 1.8.

2 Answers 2

2

You can use the template tag in python code, like this:

from django.templatetags.static import static

full_path = static('img/my_img.png')

This will also take into account use cases where the full static path is not simply the concatenation of settings.STATIC_URL with the relative path. See for instance this example in Django documentation.

Sign up to request clarification or add additional context in comments.

Comments

1

You can always import the settings file

from django.conf import settings
...

if my.condition:
    return ("<img src='%s/img/my_img.png' />" % (settings.STATIC_URL)) + obj.nam

1 Comment

This answer do not take into account use cases where the full static path is not simply the concatenation of settings.STATIC_URL with the relative path. See for instance this example in Django documentation.

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.