Nobsyde
Nobsyde

Reputation: 13

Sending a POST request through Javascript on Django - failed to retrieve data

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?

Upvotes: 1

Views: 124

Answers (2)

ndpu
ndpu

Reputation: 22561

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'
              }})

Upvotes: 1

blue note
blue note

Reputation: 29071

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.

Upvotes: 0

Related Questions