Django admin raises CSRF verification failed

igoris picture igoris · Oct 3, 2012 · Viewed 7.6k times · Source

I've started new django project and enabled admin app. I can login to admin site but when I'm trying to add/change site or user I'm getting

CSRF verification failed. Request aborted.
Reason given for failure:
CSRF token missing or incorrect.

That's what I have in settings.py:

TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)

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',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)

When I'm looking at admin page source I see

<input type='hidden' name='csrfmiddlewaretoken' value='T9Mfk1LRXi5jPE2dh5jcvdKwzYM6Iy5I' />

there

I have Django version 1.4.1

Answer

Ian Clelland picture Ian Clelland · Oct 3, 2012

Have you overridden the CSRF_COOKIE_DOMAIN setting? If the CSRF token is present in the form, and you haven't modified the source of the admin app, then the most likely scenario is that the cookie is not being set correctly.

Check the response headers of the login page to make sure that the cookie is being set correctly, and check the request headers of your login attempt to ensure that it is also being sent (and matches the value in the form).