I am getting the error "CSRF cookie not set" returned when trying to POST to a simple test app using the Django REST framework. I've tried it with Django 1.4 and the Django 1.6.2. I am using the Django REST framework v 2.3.13.
I have tried using the @csrf_exempt
decorator, but it doesn't help.
This is a very simple app, with no user registration / login etc.
Any ideas why I'm getting this error?
Update: I have updated my urls.py as shown below and it is now working!!
Here's my code:
urls.py
from django.conf.urls import patterns, url
from quickstart import views
urlpatterns = patterns('',
url(r'^api_add/$', views.api_add, name='api_add'),
)
views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def api_add(request):
return Response({"test": 'abc'})
settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
post.sh
curl -X POST -H "Content-Type: application/json" -d '
{
"name": "Manager",
"description": "someone who manages"
}' http://127.0.0.1:8000/api_add/
Django-Rest-Framework automatically adds @csrf_exempt
to all APIView
(or @api_view
).
Only exception is the SesssionAuthentication
which forces you (correctly) to use CSRF, see the docs on CSRF or the DRF source
Use the @csrf_exempt
-decorator:
from django.views.decorators.csrf import csrf_exempt
@api_view(['POST'])
@csrf_exempt
def api_add(request):
return Response({"test": 'abc'})
Update:
If you never need csrf
-checks, remove the middleware. Seach for MIDDLEWARE_CLASSES
in settings.py
and remove 'django.middleware.csrf.CsrfViewMiddleware',
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With