I am trying to let external css files work on the django 1.3 development server. I read the django’s ‘managing static files’ as well as numerous similar SO questions but I still seem to do something wrong.
Why isn’t my css style properly showing when I go to localhost:8000/page?
Directory structure
myproject
|-- manage.py
|-- settings.py
|-- urls.py
|-- app
|-- __init__.py
|-- models.py
|-- tests.py
|-- views.py
|-- static
|-- css
|-- page.css
|-- templates
|-- app
|-- page.html
myproject/views.py
import django.http
import django.template.loader
import django.template
def page_function(request):
t = django.template.loader.get_template("page.html")
c = django.template.Context()
return django.http.HttpResponse(t.render(c))
myproject/urls.py
from django.conf.urls.defaults import patterns, include, url
import myproject.app.views
urlpatterns = patterns('',(r'page/$', myproject.app.views.page_function),)
myproject/templates/app/page.css
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}page.css" />
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
myproject/settings.py
(partially)
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/myusername/Desktop/myproject/app/static",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
ROOT_URLCONF = 'myproject.urls'
TEMPLATE_DIRS = (
'/home/myusername/Desktop/myproject/templates/app',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
)
From the django docs:
Instead of
You’ll want to use:
Also note that the directory structure is maintained with static files, so because your page.css is in a subdirectory of ‘static’, you’ll need to load it in the template as ‘css/page.css’.