So I've carefully read this page https://docs.djangoproject.com/en/1.2/howto/static-files/. I have done the following:

In urls.py

from django.conf.urls import patterns, include, url
from views import *

urlpatterns = patterns('',
                       ('^SearchFoos$', searchForFoos),
                       ('^Foo/(\d+)$', showFoo),
                       (r'^static/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/home/david/workspace/fooapp/fooapp/static'}),
)

I have a file called site.css at the location /home/david/workspace/fooapp/fooapp/static/css.

In the template

My template contains the following link:

<link href="/static/css/site.css" rel="stylesheet" type="text/css" />

Yet when I load the page using the runserver, Firefox gives me a 404 for the CSS file. It's trying to get the file from the location http://localhost:8000/static/css/site.css, which is what I would have expected.

I've stared at this and stared at it and can't see the problem. Can anyone help (I'm totally new to python and django).

有帮助吗?

解决方案

Check out the django 1.4 docs on serving static files in development. If you're not using the built in django server you'll need to add this to your urls.py file. making sure that your STATIC_DIRS and STATIC_URL settings are properly configured.

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# ... the rest of your URLconf goes here ...

urlpatterns += staticfiles_urlpatterns()

As noted in the docs, you'll need to make sure DEBUG = True in your settings.py.

If you're using the built in django server you just need to put your static files in a directory called static at the top level of your app and it will just work.

其他提示

try:

(r'static/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/home/david/workspace/fooapp/fooapp/static'}),
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top