Django Rest Framework, ajax POST works but PATCH t

2019-06-15 18:36发布

I am porting my project to Django Rest Framework to make a proper REST Api for my project, I think it helps a lot designing the API and making it robust but I am running into a problem :

I have a entry model and associated ListCreateAPIView and RetrieveUpdateDestroyAPIView views. I can successfully post a new entry instance in the list through an ajax request and providing the csrfmiddlewaretoken as I would do in regular Django View.

    POST entries/

Now I am trying to apply a patch to an existing instance using the same csrfmiddlewaretoken like so:

    PATCH entries/3

The response status code is then 403 FORBIDDEN vith error CSRF Failed: CSRF token missing or incorrect although I checked in firebux that csrfmiddlewaretoken is in the request data.

I don't what is wrong and I cannot find out where in the code is the request rejected.

Note: I can patch the object with the Django Rest Framework browsable api.

I hope someone can help. Thanks. Olivier

EDIT

I was digging into the code to see where the rejetion of the PATCH request occurs and I found in django.middleware.csrt.py the following:

        if csrf_token is None: #<--- csrf_token is defined
            # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
            # and in this way we can avoid all CSRF attacks, including login
            # CSRF.
            return self._reject(request, REASON_NO_CSRF_COOKIE)

        # Check non-cookie token for match.
        request_csrf_token = ""
        if request.method == "POST": #<--- This fails but request_csrf_token is in request.DATA
            request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')

        if request_csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX,
            # and possible for PUT/DELETE.
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

The second test fails because it is not a POST request but the information required is in request.DATA. So it seems that django is not keen to accept PATCH request. What do you think would be the best way to go around this?

Would you recommend using a different authentication system (there are some in Django-rest-framework documentation)?

EDIT2

I found out a solution: I observed that the browsable api is actually sending a POST request but with a parameter _method="PATCH", so I did the same with my ajax request and it works fine.

I don't know if it is the right way to do, any feedback and opinion is welcome!

EDIT3

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",
   ...
});

3条回答
劳资没心,怎么记你
2楼-- · 2019-06-15 18:55

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.

查看更多
ら.Afraid
3楼-- · 2019-06-15 19:14

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!

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-15 19:20

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",
...
});
查看更多
登录 后发表回答