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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With