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>
- How to Configure a BIND Server on Ubuntu - March 15, 2018
- What is a BGP Confederation? - March 6, 2018
- Cisco – What is BGP ORF (Outbound Route Filtering)? - March 5, 2018
Want to become a Django expert?
Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial