0

I want to update an object via UpdateAPIView using Django Rest framework

$('#update-form').on('submit', function(event){
    event.preventDefault();
    console.log( $( this ).serialize() );
    data = new FormData($('#update-form')[0]);
    $.ajax ({
        type: "PATCH",
        url: $( this ).attr( 'action' ),
        data: data,
        processData: false,
        contentType: false,

        success: function(json) {
            console.log(json);
            console.log('success');
        },

        error: function(xhr, errmsg, err) {
            console.log(xhr.status + ": " + xhr.responseText)
        }
    });
})

Upon submitting, I get the error response:

403: {"detail":"CSRF Failed: CSRF token missing or incorrect."}

I have {% csrf_token %} in the templates, and verify its there, either by looking at the source of the html, and printing console.log of the serialized data, where csrf token is there.

Checking the template context, the csrf token is there. Settings have the csrf middleware added.

the form html is long, but in short, the csrf is there, but the endpoint (DRF) complains of missing csrf

And by the way, creating an object using the CreateAPIView, using same form, but just the form id changed, succeeds, yet the update view doesn't work. The CreateAPIView doesn't complain of any csrf things.

KhoPhi
  • 9,660
  • 17
  • 77
  • 128
  • @chandu Okay thanks for the link. Couldn't find that in my search. But just out of curiosity, why does the createapiview sends the csrf with it, but the update doesn't? – KhoPhi May 29 '15 at 11:14
  • Hope these might help you. http://stackoverflow.com/questions/6506897/csrf-token-missing-or-incorrect-while-post-parameter-via-ajax-in-django http://stackoverflow.com/questions/8614947/jquery-and-django-csrf-token http://stackoverflow.com/questions/22063612/adding-csrftoken-to-ajax-request – chandu May 29 '15 at 11:15
  • which type of Authentication you are using? – chandu May 29 '15 at 11:22
  • @chandu I'm using default django authentication – KhoPhi May 29 '15 at 11:25
  • If you read the django rest framework documentation you get the idea. – chandu May 29 '15 at 11:38
  • possible duplicate of [CSRF Failed: CSRF token missing or incorrect](http://stackoverflow.com/questions/26639169/csrf-failed-csrf-token-missing-or-incorrect) – Kevin Brown-Silva May 29 '15 at 13:12
  • The issue is that you are not sending your token in the `X-CSRFToken` header, you appear to be sending it in the request body. – Kevin Brown-Silva May 29 '15 at 13:12
  • i think he the got solution for his problem. – chandu May 29 '15 at 13:34
  • @KevinBrown so if I'm not sending the token in x-csrftoken, why does the creating of new objects doesn't throw the csrf error. That's my issue now. Does it not enforce csrf upon saving new objects, but does so when updating an object already. There's something not adding up right somewhere. – KhoPhi May 29 '15 at 19:02

0 Answers0