Reputation: 417
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/
Upvotes: 13
Views: 35341
Reputation: 714
I had the similar issue. I tried using @csrf_exempt
but it did not work.
I changed ALLOWED_HOSTS = '*'
to ALLOWED_HOSTS = []
and it worked for me on local.
Upvotes: 0
Reputation: 6069
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',
.
Upvotes: 10
Reputation: 65
I solved this like this:
@api_view(['POST'])
@csrf_exempt
def add(request):
....
to:
@csrf_exempt
@api_view(['POST'])
def add(request):
.....
Upvotes: 2
Reputation: 4172
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
Upvotes: 5