[Fixed]-Django – taking values from POST request, JavaScript fetch API

20πŸ‘

In my experience, data sent using fetch are not located inside request.POST but rather inside request.body. There are then cases where the received data is in byte so you will need to decode it first. I suggest that you do this first:

if request.method == "POST":
    import json
    post_data = json.loads(request.body.decode("utf-8"))

Then try accessing post_data content like a normal python dictionary to get the value of tag as in post_data.get("tag")

πŸ‘€Olfredos6

3πŸ‘

As per my research request.POST won’t work it only works when there is form data, i solved my issue of accessing the data by using

 data = json.loads(request.body.decode("utf-8"))
 tag = data['tag']
 print(data)
 print(tag)

And to use json.loads() first you have to import json module.

0πŸ‘

According to documentation:

json.loads() Deserialize s (a str, bytes or bytearray instance
containing a JSON document) to a Python object using this conversion
table.

The data inside request.body is of bytes type. As json.loads already accepts bytes type of data, we do not need to decode it. So, we can simply write:

data = json.loads(request.data)
print(data) # We get data as a dictionary 

-1πŸ‘

The view received the data from the AJAX POST request and the data was in the JSON format, so we need to load it using the json module from the standard library:

import json

def my_view(request):
    if request.method == 'POST':
        # get the data from the ajax post request
        data = json.load(request) # dictionary
        tag = data.get('tag')
πŸ‘€Yacine Rouizi

-1πŸ‘

Just to mention, in my experience:

import json


def some_view(request):
    # data = request.POST  # Is going to work for the test client
    data = json.loads(request.body)  # Works, but for the test client it doesn't
πŸ‘€Matheus Costa

Leave a comment