CSRF Failed: CSRF token missing or incorrect.

3,207 views
Skip to first unread message

Кирилл Тарасенко

unread,
Mar 4, 2014, 7:29:16 AM3/4/14
to django-res...@googlegroups.com
Hi!
My django-rest-framework settings are:

REST_FRAMEWORK = {
    'DEFAULT_MODEL_SERIALIZER_CLASS':
        'rest_framework.serializers.HyperlinkedModelSerializer',
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
        ],
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    ),
}

My custom user is authenticating through API view, and then he can post notes. The view I use for this looks like this:

class AddNoteAPI(generics.CreateAPIView):
    model = UserNote
    serializer_class = AddNoteSerializer
    permission_classes = (IsAuthenticated,)

I use AJAX to send POST like this:

$('a.save-icon').click(function (event) {
        event.preventDefault();
        console.log($textarea.val());
        $.ajax({
            type: 'post',
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            url: add_note_url,
            headers: {
                HTTP_X_CSRFTOKEN: getCookie('csrftoken')
            },
            data: JSON.stringify({
                note: $textarea.val()
            }),
            beforeSend: function() {
                $textarea.removeClass('error');
            },
            statusCode: {
                200: function(response) {
                    console.log(response);
                },
                400: function(response) {
                    console.log(response);
                },
                403: function() {
                    console.log(response);
                }
            }
        });
    });

And I get an error 
{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

Why this is happening?
Thanks in advance.

Anoop Malav

unread,
Mar 4, 2014, 7:41:57 AM3/4/14
to django-res...@googlegroups.com
https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax

Your request header should be X-CSRFToken not HTTP_X_CSRFTOKEN.

Кирилл Тарасенко

unread,
Mar 4, 2014, 7:47:52 AM3/4/14
to django-res...@googlegroups.com
thank you

Вівторок, 4 березня 2014 р. 14:41:57 UTC+2 користувач Anoop Malav написав:
Reply all
Reply to author
Forward
0 new messages