Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of MIDDLEWARE_CLASSES in django

Tags:

python

django

the djangobook has this section

To activate this CSRF protection, add 'django.contrib.csrf.middleware.CsrfMiddleware' to the MIDDLEWARE_CLASSES setting in your settings file. This middleware needs to process the response after SessionMiddleware, so CsrfMiddleware must appear before SessionMiddleware in the list (because the response middleware is processed last-to-first).

however ,djangoproject page tells it different

MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', )

It is a bit confusing..Do the CsrfViewMiddleware process the response after SessionMiddleware now?Can someone clarify?

like image 361
damon Avatar asked Nov 22 '25 12:11

damon


1 Answers

From the Django docs:

Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)

Source: https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#how-csrf-works

Here's my Middleware list in a freshly generated Django project (1.3.1):

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

So, yes, Django processes the CSRF Middleware after the session middleware now.

The Django Book is severely outdated - I wouldn't use it as a resource for learning Django these days. The Django tutorial, on the other hand, is a wonderful resource.

like image 72
Todd Avatar answered Nov 24 '25 04:11

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!