D3v5 and Django Rest Framework

2019-08-08 05:12发布

问题:

I'm having some trouble getting the following AJAX call to work. I'm using D3 version 5 to make the following POST request to a Django REST Framework (DRF) ModelViewSet (version 3.x) view. DRF provides the list of tasks under the path /gander/tasks/ and allows one to create a new one by POST'ing to the same path. I believe I'm retrieving the CSRF token correctly but I'm not sure I'm formulating the POST properly.

d3.json("/gander/tasks/?format=json",
 {method:"POST",
  headers:{
   "Content-type": "application/json; charset=UTF-8",
   "X-CSRFToken" : Cookies.get('csrftoken') },
  body:JSON.stringify({
   "parent": null,
   "name"  : "",
   "time"  : null}),
 })
 .then(json => {console.log(json);})
 .catch(error => {console.log(error);});

I've gone through the Django A.J.A.X. docs, D3 examples and a stack of S.O. Questions but they all refer to the D3-Request interface and I can't find any examples using the newer D3-Fetch API as above.

回答1:

Thanks to @dkarchmer I figured I needed more information on the server side. The following mixin was rather useful for showing both the data received and transmitted.

class AjaxLoggingMixin(object):

    def finalize_response(self, request, response, *args, **kwargs):
        print(request.data)
        print(response.data)
        return super().finalize_response(request, response, *args, **kwargs)

It turns out the requests were going through correctly but were malformed and Django was rejecting them returning either 4XX error codes. In particular

  • 403 results when the user isn't authenticated or user authentication isn't setup properly.

  • 400 results when the data is malformed.