问题
I'm running a django 1.4.1 app.
I didn't realize that just including django.contrib.staticfiles
into INSTALLED_APPS
in your settings is enough to get static files served while settings.DEBUG
is True, i.e., you don't have to manually add anything to your urls file.
I also noticed that this bypasses the django middleware. Does anyone know how or why this happens?
I just created a blank new project, my views.py:
from django.http import HttpResponse
def index(request):
html = '<html><body>Logo: <img src="/static/logo.gif"></body></html>'
return HttpResponse(html)
My urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'testapp.views.index', name='home'),
)
My settings.py has specified a directory to look for static files, and it also has this added:
MIDDLEWARE_CLASSES = (
'testapp.middleware.TestMiddleware',
...
)
Using this middleware:
from __future__ import print_function
class TestMiddleware(object):
def process_request(self, request):
print("[REQUEST]", request.path)
And when I make a request, this gets printed out:
[REQUEST] /
[18/Jan/2013 15:30:27] "GET / HTTP/1.1" 200 60
[18/Jan/2013 15:30:27] "GET /static/logo.gif HTTP/1.1" 200 2190
[REQUEST] /favicon.ico
Is it something to do with how the test server starts up?
回答1:
I just figured this out after posting…
If you're using django-admin.py runserver
or python manage.py runserver
, then it does some extra magic to add a staticfiles handler that your regular middleware can't touch.
You can disable this by running django-admin.py runserver --nostatic
— see the django docs
And when you do --nostatic
it will fall back to the urls in your app, such as if you include staticfiles_urls() directly with:
urlpatterns += staticfiles_urlpatterns()
then your middleware will run for those urls (and of course all your others).
回答2:
Found this issue when trying to modify request.path with middleware.
Discovered urls resolve against request.path_info
not request.path
来源:https://stackoverflow.com/questions/14408017/does-django-staticfiles-skip-the-middleware