Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get the static files URL in view

People also ask

What is static URL in Django?

"STATIC_ROOT" sets the absolute path to the folder where static files used for the apps and admin in a django project are stored and this command below creates the folder and collects static files from the apps and admin in a django project into the folder (*Setting "STATIC_ROOT" never ever influence to static file URL ...

Where are static files Django?

Make sure that django. contrib. staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE .

What is {% load static %} in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.


# Older Django <3.0 (also deprecated in 2.0):
from django.contrib.staticfiles.templatetags.staticfiles import static

# Django 3.0+
from django.templatetags.static import static

url = static('x.jpg')

url now contains '/static/x.jpg', assuming a static path of '/static/'


EDIT: If you're on Django >=3.0, refer to Django get the static files URL in view instead. This was answered with Django 1.X version.

dyve's answer is good one, however, if you're using "cached storage" on your django project and final url paths of the static files should get "hashed"(such as style.aaddd9d8d8d7.css from style.css), then you can't get a precise url with django.templatetags.static.static(). Instead, you must use template tag from django.contrib.staticfiles to get hashed url.

Additionally, in case of using development server, this template tag method returns non-hashed url, so you can use this code regardless of that the host it is development or production! :)

from django.contrib.staticfiles.templatetags.staticfiles import static

# 'css/style.css' file should exist in static path. otherwise, error will occur 
url = static('css/style.css')

From Django 3.0 you should use from django.templatetags.static import static:

from django.templatetags.static import static

...

img_url = static('images/logo_80.png')

here's another way! (tested on Django 1.6)

from django.contrib.staticfiles.storage import staticfiles_storage
staticfiles_storage.url(path)