fir3net
PPS-Firenetbanner-780.5x190-30-03-17

Django - CSRF verification failed. Request aborted.

Issue

When trying to access your Django site within CSRF configured you receive the following via a Forbidden (403) HTTP error message:

CSRF verification failed. Request aborted.
No CSRF or session cookie.

Solution

In my scenario I found that the order of settings.MIDDLEWARE_CLASSES was incorrect. Below shows you an example

settings.py

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

views.py

from django.shortcuts import render_to_response
from django.template import RequestContext

def input(request):
    return render_to_response('input.html', context_instance=RequestContext(request))

def output(request):
    if 'q' in request.POST:
        message = request.POST['q']
    else:
        message = 'error'
    return render_to_response('output.html', {'message': message}, context_instance=RequestContext(request))

template

<html>
 <body>

  <form action="/output/" method="POST">
  {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="input">
  </form>

 </body>
</html>

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001