6

I've been like an hour searching how to reference static files in django, but I only found how to do it in templates. In my project, I succeeded in referencing static files in my templates, but I DON'T want to do it in templates, I want to do it in my .py files.

I think that i have to import static from somewere, I've tried with this:

from django.templatetags.static import static
from django.conf.urls.static import static

And trying to reference it like this

'<a href=/url> <img  src="{{ STATIC_URL }}image.png" ></a>'

I've tried all possible combinations like

{% static image.png %}
{{static image.png}}

and so on...

Thanks!

3 Answers 3

9
from django.templatetags.static import static
'<a href=/url> <img  src="{0}" ></a>'.format(static("image.png"))

Note that django.templatetags.static is actually a function. The template engine calls that function when you use the template tag.

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

2 Comments

@Danidestroyer Could you accept one of the answers? That way, other people will know this question has been answered.
For me this shows path correctly but imgs in admin never load
1

If you want to find the actual file on disk, you can use the finders class of the staticfiles app:

>>> from django.contrib.staticfiles import finders
>>> finders.find("icons/exclamation.svg")
'C:\\<project folder>\\<project name>\\<app name>\\static\\icons\\exclamation.svg'

Django Docs

Comments

-2

You can read django configuration to get STATIC_URL which contains URL base part for static files:

from django.conf import settings
import urlparse

print '<a href=/url> <img src="%s"></a>' % urlparse.urljoin(settings.STATIC_URL, 'image.png')

3 Comments

Code snippets on their own are not very informative. Please explain what the code does, why you wrote it that way, and how you expect it to work
I've add a link to documentation
This doesn't work with various static file storage backends

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.