How to load CSS into Django templates?

I'm having trouble loading CSS for my Django template.

I have the following settings:

STATIC_ROOT = '' STATIC_URL = '/css/' STATICFILES_DIRS = ("/css") INSTALLED_APPS = ( 'django.contrib.staticfiles', ) 

Do I need to use both static_url and staticfiles_dirs ?

urls.py -

 urlpatterns = patterns('', (r'^$',homefun), ) 

views.py -

 def homefun(request): return render_to_response('home.html') 

And the parent template is base.html, which loads css.

 <link rel="stylesheet" type="text/css" href="/css/style.css" /> 
+4
source share
4 answers

Your STATICFILES_DIRS = ("/css") should be STATICFILES_DIRS = ("/path/to/your/css", ) (pay attention to the final comma - this is necessary because (eggs) evaluates the value of eggs , but the final comma forces it to evaluate tuple).

+8
source

You need to use {{ STATIC_URL }} as a variable in templates, for example:

 <link rel="stylesheet" href="{{ STATIC_URL }}style.css"> 

Django's official documentation provides a good explanation of serving static files.

You must set the STATIC_ROOT variable. Using STATICFILES_DIRS is optional, by default Django searches in the static directories of all your applications.

+6
source

STATIC_URL is for the URL of your static media (for which the web server will serve static media in the browser), and STATICFILES_DIRS is the list of folders on your computer (where the web server will find the files to serve). AFAIK the latter should use absolute paths, not relative, maybe that’s why it doesn’t work for you.

+1
source

This solution worked for me.

I am converting code from python2.7 to python3.4 and have been unable to get static files to display after conversion.

I changed the script(src='#{STATIC_URL}js/libs/jquery-2.1.1.min.js') to script(src='{{STATIC_URL}}js/libs/jquery-2.1.1.min.js') , and now everything works fine.

0
source

Source: https://habr.com/ru/post/1397163/


All Articles