Danidestroyer
Danidestroyer

Reputation: 97

Reference static files in django in .py files ( NOT in templates)

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!

Upvotes: 6

Views: 1714

Answers (3)

MinchinWeb
MinchinWeb

Reputation: 706

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

Upvotes: 1

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

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')

Upvotes: -2

knbk
knbk

Reputation: 53699

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.

Upvotes: 9

Related Questions