0

I'm trying to send POST with some variables to Django.

Send from JS:

    function sendStatistic(csrftoken, song_id, answer) {
    fetch('request/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrftoken,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: {
             'Song-Id': song_id,
            'Answer': answer
        ,},
    });

}

And try to capture 'Song-Id' and 'Answer' in Django but:

request.POST.get('Answer') 

returns None

what am I doing wrong?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • If it returns None that means not found anything, can you also share your template? – Sunderam Dubey Jun 09 '22 at 13:45
  • You set content type to application/JSON but read data urlencoded. Make sure you encode the data consistently in all 3 places – mousetail Jun 09 '22 at 14:07
  • Does this answer your question? [How do I POST a x-www-form-urlencoded request using Fetch?](https://stackoverflow.com/questions/35325370/how-do-i-post-a-x-www-form-urlencoded-request-using-fetch) – mousetail Jun 09 '22 at 14:12
  • If you want to use JSON instead check out https://stackoverflow.com/questions/7368669/getting-a-json-request-in-a-view-using-django – mousetail Jun 09 '22 at 14:14

2 Answers2

1

now all is ok. I have changed 'Content-Type' and add 'new URLSearchParams' into body

 function sendStatistic(csrftoken, song_id, answer) {
    fetch('request/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrftoken,
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            'Song-Id': song_id,
            'Answer': answer,
        }),
    });
}

Now I can get my variables in django

0

Try request.body instead of request.POST

pzutils
  • 490
  • 5
  • 10