What I am trying to do ?
I am trying to send a post request with data to a Django view using fetch API like this:
javascript:
const data = {
search_text: "",
months: 6,
property_type: "all"
};
const headers = {
'Accept': 'application/json',
'Content-Type':'application/json',
'X-Requested-With':'XMLHttpRequest'
}
fetch("some-url", {method: "POST", headers: headers, body: JSON.stringify(data)})
.then((response) => response.json())
.then((data) => console.log(data));
views.py:
class MyView(View):
def post(self, request, *args, **kwargs):
print("request: ", request.POST)
# do stuff with post data
urls.py:
re_path(r"^my_view/$", login_required(csrf_exempt(MyView.as_view())), name="my_view"),
Problem
When I try to access the post data in my Django view I get empty QueryDict and the output of the terminal is this:
request: <QueryDict: {}>
[06/Jan/2022 06:48:19] "POST /my_app/my_view/ HTTP/1.1" 200 114
Forbidden (CSRF token missing or incorrect.): /inbox/notifications/api/unread_list/
[06/Jan/2022 06:48:22] "{"search_text":"","months":"6","property_type":"all"}GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 403 12291
If you notice at the last line the post data seems to get added in the terminal why is that happening ? also why I get Forbidden (CSRF token missing or incorrect.) even when I am using csrf_exempt in the urls ?
I have tried looking it up and nothing seems to work. We are using react and I know axios can also be used but it should work with fetch API why isn't it working please help.
Edit:
Even after adding csrf token like mentioned in the docs and removing csrf_exempt from the urls I still get the same issue.
This is because your view is protected by a CSRF-protection-middleware.
You have two possibilities:
Okay fixed the issue it seems the data I was looking for was not in request.POST but instead in request.body did the following changes:
import json
class MyView(View):
def post(self, request, *args, **kwargs):
print("request: ", json.loads(request.body))
# do stuff with post data
request.body returns byte string so need to convert that to json with json.loads for more info read docs