Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "CSRF cookie not set" when POST to Django REST framework?

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/                                               
like image 821
smithy Avatar asked Apr 02 '14 13:04

smithy


2 Answers

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

like image 179
Denis Cornehl Avatar answered Nov 18 '22 22:11

Denis Cornehl


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',.

like image 10
tjati Avatar answered Nov 18 '22 22:11

tjati