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")
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
- Django β When should I use signals and when should I override save method?
- Django and service workers β serve "sw.js" at application's root url
- Django can't access raw_post_data
-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')
- Convert data on AlterField django migration
- How to test (using unittest) the HTML output of a Django view?
- Django form errors prints __all__
- Django Admin Drop down selections
-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
- Force evaluate a lazy query
- How to create new resource with foreign key in TastyPie
- Is there any list of blog engines, written in Django?