[Fixed]-Django Rest Framework, ajax POST works but PATCH throws CSRF Failed: CSRF token missing or incorrect

6👍

I finally add this as an answer.

So, after more reading, I discovered (I already kind of knew..) that because some browsers do not support requests like PUT, PATCH, DELETE, the way to go is to send a post request with X-HTTP-Method-Override in the header.

So the good way to go I think is to do the following:

$.ajax({
    headers: {
        'X-HTTP-Method-Override': 'PATCH'
    },
    type : "POST",
...
});

7👍

I also meet the same question, I learn from @overlii solution problem method. I use django rest framework web interface to do put/patch, and I find the HTTP Request Headers Info like below:
HTTP Request Headers

From this image, we can find X-CSRFTOKEN header, so I set ajax header info like below:

$.ajax({
        headers: {
            'X-CSRFTOKEN': '{{ csrf_token }}'
        },
        type: "PATCH",
        dataType: "json",
        url: "/api/path/",
        data: "",
        success: function(data){
                
        }
});

I use this way to send patch request and find this can run rightly!

0👍

This isn’t a direct solution to your problem but this should provide some context and provide a possible solution.

Django does not support the HTTP PATCH method and throws away all data including the CSRF token. A possible workaround is to change the method to POST, force Django to reprocess the request and change the method again. This is a bit dirty but works, example code as used by Django Piston is provided here:

def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.

The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if request.method == "PUT":
    # Bug fix: if _load_post_and_files has already been called, for
    # example by middleware accessing request.POST, the below code to
    # pretend the request is a POST instead of a PUT will be too late
    # to make a difference. Also calling _load_post_and_files will result 
    # in the following exception:
    #   AttributeError: You cannot set the upload handlers after the upload has been processed.
    # The fix is to check for the presence of the _post field which is set 
    # the first time _load_post_and_files is called (both by wsgi.py and 
    # modpython.py). If it's set, the request has to be 'reset' to redo
    # the query value parsing in POST mode.
    if hasattr(request, '_post'):
        del request._post
        del request._files

    try:
        request.method = "POST"
        request._load_post_and_files()
        request.method = "PUT"
    except AttributeError:
        request.META['REQUEST_METHOD'] = 'POST'
        request._load_post_and_files()
        request.META['REQUEST_METHOD'] = 'PUT'

    request.PUT = request.POST

I have successfully used this fix (with some modifications) and although it feels a bit dirty it seems to be a very usable solution.

Alternatively you could use do method overloading in the POST data. Again not the prettiest solution but very workable.

I would love for someone to propose a better solution.

Leave a comment