1

I'm trying to send a POST request to my Django view using plain javascript (I don't want any unnecessary libraries involved). The data is not sent through a form, but by using fetch. For now I just want to be able to manipulate the request.POSTin my views.py, nothing more.

Here's my code:
Javascript

let article = document.querySelector('article')
articleId = article.getAttribute('data-product-id')

# some other stuff
fetch("{% url 'shop:shoplist' 1 %}", { 
              method: 'POST',
              dataType: "application/json", 
              data: {'article_id': articleId},
              headers: {'X-CSRFToken': csrf_token}
              })

Python

if request.method == 'POST':
    testing = request.POST
    return JsonResponse({'test': testing})

The request is sent, the csrftoken is received correctly, but the request.POST returns just <QueryDict: {}>, instead of what I'm expecting (headers, data...).

I've searched and found a lot of similar questions, the most similar one being this one, but still I can't seem to find a solution.

Any idea?

2 Answers 2

1

Try to add 'content-type' to headers in fetch call (instead of dataType parameter) and change data parameter to body with stringified object:

fetch("{% url 'shop:shoplist' 1 %}", { 
              method: 'POST',
              body: JSON.stringify({'article_id': articleId}),
              headers: {
                  'X-CSRFToken': csrf_token,
                  'Content-Type': 'application/json'
              }})
Sign up to request clarification or add additional context in comments.

2 Comments

@Nobsyde try with JSON.stringify
oh wow sorry I didn't see you also changed the data (now body) parameter, it works! To be more precise, both you and @blue_note have it right: there were 2 errors: (1) using data instead of body and (2) asking for request.POSTinstead of request.body. Thank you both!
0

The request.POST contains only the parameters that are form encoded. Since your data type is application/json they are empty. The request.body contains the actual json data.

2 Comments

I've tried to change the code with: testing = request.body print(testing) but the printed value is now b''
@Nobsyde: add "Content-Type": "application/json; charset=utf-8" to the headers. I'm not sure what dataType does in your request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.