Failed to check CSRF. Request aborted - Django, POST
I am using server: Django, Gunicorn, ngnix, postgresql
Client: Chrome Advanced Rest Client
views.py
from django.views.decorators.csrf import csrf_exempt, **ensure_csrf_cookie** # Newly added
from django.http import HttpResponse
**@ensure_csrf_cookie** # newly added
def hello(request):
return HttpResponse("Hello world")
def hi(request):
return HttpResponse("Hi World")
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
def addUser(request):
if request.method == 'POST':
# Convert JSON to python objects and
# store into the DB
print 'Raw Json "%s"' % request.body
#return HttpResponse("%s" %request.body)
return HttpResponse("Thank God")
url.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from requests import hello, hi, addUser, display_meta
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^hello/$', hello),
url(r'^hi/$', hi),
url(r'^admin/', include(admin.site.urls)),
url(r'^addPatient/$', addUser),
url(r'^displaymeta/$', display_meta),
)
manage.py
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dbTransactions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
27,18 35%
From Advance Rest Client:
a) GET to hi works fine without error b) POST to addUser gives " CSRF check failed. Request aborted "
What I have tried:
- @csrf_exempt in views. - No change in POST of the same error
- Inserting X-CSRF token - in POST header - No changes in POST same error
I would really appreciate help with this. I had read:
source to share
Thanks for the answer. I learned the following about CSRF clients, Django and Chrome Advanced Rest API.
and. CSRF - Cross-Site Request Forgery is a way to protect malicious transactions, especially POST, PUT, DELETE on an authenticated connection between a client and a server.
b. Django allows GET with CSRF token, but it doesn't work for POST, PUT, or DELETE.
from. To get the CSRF token in the response for GET, you can use @ensure_csrf_cookie, which will make sure the response has a CSRF token.
e. For POST from Chrome Advanced REST Client, you must use X-CSRFTOKEN and the token obtained from the GET command response.
source to share