19👍
You’re posting JSON, which is not the same as form-encoded data. You need to get the value of request.body
and deserialize it:
data = json.loads(request.body)
custom_decks = data['custom_decks']
7👍
As I was having problems with getting JSON data from HttpRequest directly with the code of the other answer:
data = json.loads(request.body)
custom_decks = data['custom_decks']
error:
the JSON object must be str, not 'bytes'
Here is an update of the other answer for Python version >3:
json_str=((request.body).decode('utf-8'))
json_obj=json.loads(json_str)
Regarding decode(‘utf-8’), as mention in:
RFC 4627:
“JSON text shall be encoded in Unicode. The default encoding is
UTF-8.”
I attached the Python link referred to this specific problem for version >3.
- Matplotlib: interactive plot on a web server
- Testing a custom Django template filter
- Separating Django App Views
- Styling django non-field errors on forms
3👍
python 3.6
and django 2.0
:
post_json = json.loads(request.body)
custom_decks = post_json.get("custom_decks")
json.loads(s, *, encoding=None,...)
Changed in version
3.6
:s
can now be of typebytes
orbytearray
. The input encoding should beUTF-8
,UTF-16
orUTF-32
.
From python 3.6
NO need request.body.decode('utf-8')
.
- Django queryset __contains case sensitive?
- Determine empty template variable in Django
- How to properly query a ManyToManyField for all the objects in a list (or another ManyToManyField)?
2👍
Since HttpRequest has a read() method loading JSON from request is actually as simple as:
def post(self, request, *args, **kwargs):
import json
data = json.load(request)
return JsonResponse(data=data)
If you put this up as a view, you can test it and it’ll echo any JSON you send back to you.
- Django-templates: Why doesn't {% if "string"|length > 10 %} work at all?
- Django-tastypie: Any example on file upload in POST?
- Create a Session in Django