I'm trying to post data from a form built in React over a Django-Rest-Framework API and have run into an issue with the authentication. I can post fine if I turn off authentication on the API View, so I think I've narrowed it down to how I'm passing the data in the form.
My DRF view looks like this:
class PropertyListCreate(generics.ListCreateAPIView):
authentication_classes = (SessionAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = models.Property.objects.all()
serializer_class = serializers.PropertySerializer
The handler for the Submit is below.
handleSubmit = e => {
e.preventDefault();
const { name, type, address, city, state, zip_code } = this.state;
const property = { name, type, address, city, state, zip_code };
const conf = {
credentials: 'include',
method: 'POST',
body: JSON.stringify(property),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.load('csrftoken')
}
};
fetch(this.props.endpoint, conf).then(response =>
console.log(response),
console.log(conf)
);
};
When I attempt to post with the above code, I get a 400 Error - and if I remove the 'X-CSRFToken': cookie.load('csrftoken'), I get a 403 Error (Forbidden). My understanding of a 400 Error is that the request was badly formatted, so I'm thinking that I'm sending the csrf token incorrectly?
This is the output from console.log(response):
Response {type: "basic", url: "http://127.0.0.1:8000/api/properties/",
redirected: false, status: 400, ok: false, …}
The response after removing the X-CSRFToken from the headers:
Response {type: "basic", url: "http://127.0.0.1:8000/api/properties/",
redirected: false, status: 403, ok: false, …}