Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load CSS in 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 also staticfiles_dirs?

urls.py is

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

views.py is

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

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

<link rel="stylesheet" type="text/css" href="/css/style.css" />
like image 648
John Avatar asked Dec 06 '22 16:12

John


2 Answers

Your STATICFILES_DIRS = ("/css") should actually be STATICFILES_DIRS = ("/path/to/your/css", ) (note the trailing comma — necessary because (eggs) evaluates to the value eggs, but the trailing comma forces it to evaluate to a tuple).

like image 137
David Wolever Avatar answered Dec 23 '22 18:12

David Wolever


You need to use {{ STATIC_URL }} as variable in templates, like so:

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

Official Django documentation have a good explanation about serving static files.

You must set STATIC_ROOT variable. Using STATICFILES_DIRS is optional, by default Django search within static directories of all your apps.

like image 22
neoascetic Avatar answered Dec 23 '22 18:12

neoascetic