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?
Activating middleware To activate a middleware component, add it to the MIDDLEWARE list in your Django settings. A Django installation doesn't require any middleware — MIDDLEWARE can be empty, if you'd like — but it's strongly suggested that you at least use CommonMiddleware .
django. contrib. staticfiles collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production.
Middleware and decorators are similar and can do the same job. They provide a means of inserting intermediary effects either before or after other effects downstream in the chain/stack.
Configuring static filesMake sure that django.contrib.staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE . Store your static files in a folder called static in your app.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With