I'm a beginner trying to figure how to use both Django and Fetch api.
I was trying to follow this question Django - taking values from POST request, JavaScript fetch API
To figure out how to POST a form to a Django view, and access the data from the view. I'm not sure if my header has an issue.
my html form
<form class="basicform">
<label for="nametextbox">Change First Name</label>
<input type="text" name="nametextbox">
</form>`
My fetch POST request
function postForm(id, form){
var formData = new FormData (form);
let response = fetch("{% url 'fetch-ppl' '12345' %}".replace('12345',id), {
method: 'POST',
body: formData,
headers: { 'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
"X-CSRFToken": getCookie("csrftoken") },
})
.then(response => response.json())
.then(data=>{
console.log(data);
})
return 'Post Done';
}
My POST view, that I'm trying to send the form data to
def post_form_rest(request, pk):
ppl = PersonalData.objects.get(id=pk)
serializer = PersonalDataSerializer(ppl,many=False)
if (request.method == 'POST'):
print("It's a Post Request")
print(request.POST);
print("Contents of Body")
print(request.body);
data = ["post request done"]
return JsonResponse(data, safe=False)
print("it wasn't a post request")
return JsonResponse(serializer.data)
My problem is when I send my POST request, the django view doesn't detect any POST data at all, it just skips to the end where it gives me a json response of the initial model object. (I don't get any print statements that "it's a post request")
I'm having trouble accessing the formdata that I'm trying to send. The request.POST is empty and so is request.body
2023-08-25 20:52:14 It's a Post Request
2023-08-25 20:52:14
2023-08-25 20:52:14 <QueryDict: {}>
2023-08-25 20:52:14
2023-08-25 20:52:14 Contents of Body
2023-08-25 20:52:14
2023-08-25 20:52:14 b'------WebKitFormBoundary3j9PtnVhAWSkfB14--\r\n'
2023-08-25 20:52:14
If I visit the url, does spit out the JSON.
For reference I set up a demo, but it'll probably be deleted evetually:
Form: https://alisatlee.pythonanywhere.com/ You can check the console.log, just type gibberish in any of the boxes and hit enter.
I want to post a request to here: https://alisatlee.pythonanywhere.com/fetch-ppl/1/