Unable to serve content from /static URL root in Django development server
I was absolutely baffled for a good 30 minutes, but I think my issues must be related to change in Django 1.3.
My urls.py looks like this:
if settings.DEBUG:
urlpatterns += pat开发者_如何学运维terns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
(r'^admin_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.ADMIN_MEDIA_ROOT}),
)
If I visit /static/, I get a file listing. For example, in my root directory there is a file "iphone.png". Going to /static/iphone.png I get a 404 message.
If I change that section to:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^otherstatic/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
(r'^admin_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.ADMIN_MEDIA_ROOT}),
)
Everything related to /otherstatic/ works wonderfully.
I should also add there were no problems with /media/ or /admin_media/.
Is this related to Django's new staticfiles app? (If so, who thought it was a good idea to completely break this very simple use case?)
Thanks!
In Django 1.3, with django.contrib.staticfiles
in your INSTALLED_APPS
, the framework will look for all static files under all apps which have a static folder.
Read the first point, second line carefully.
Here's an example:
project/
yourapp/
static/
iphone.png
settings.py
Assuming yourapp
is in your INSTALLED_APPS
, you should be able to access the iphone.png
image with just the following url:
http://localhost:8000/static/iphone.png
For your case, if you want staticfiles
app to search for files under project/static/
, you will need to add the following to your settings.py
:
import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'static'),
)
Be careful with the above, make sure that none of the paths in STATICFILES_DIRS
are a match to the path you set in STATIC_ROOT
. The latter is mainly used in production.
Feel free to remove the static
line from your project urls.py
after setting STATICFILES_DIRS
.
Unless you are using a different development server, you shouldn't need to add anything to your urlconf for serving staticfiles in your STATIC_ROOT dir.
http://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#s-static-file-development-view
This view is automatically enabled by runserver (with a DEBUG setting set to True). To use the view with a different local development server, add the following snippet to the end of your primary URL configuration:
精彩评论