1

I have a jquery POST function like this :

 $.post(data_send_url,
    {
        all_letters:["A","B","C"]
    },
    function(data, status){
        alert(data);
});

In the server side when I access it using request.data in a Django view function I get <QueryDict: {'all_letters[]': ['e', 'r', 'p']}>. How can I get a Python list like all_letters = ['e','r','p'] ?

2
  • Did you tried request.data[all_letters] ? Or json.loads ? Commented Jun 10, 2018 at 11:07
  • request.data["all_letters"] gives key error,request.data.get("all_letters") gives TypeError: the JSON object must be str, bytes or bytearray, not 'QueryDict' Commented Jun 10, 2018 at 11:11

3 Answers 3

2

This code solved my problem:

$.post(data_send_url,
    {
        all_letters:JSON.stringify(["A","B","C"]), //JSON.stringify added
    },
    function(data, status){
        alert(data);
});

And in views.py

json.loads(request.data.get("all_letters"))
json.loads(request.POST["all_letters"]) #both of these work fine
Sign up to request clarification or add additional context in comments.

Comments

1

can you try to stringify the array and after this use json.loads ?

$.post(data_send_url,
    {
        all_letters: JSON.stringify(["A","B","C"])
    },
    function(data, status){
        alert(data);
});

# and after this use json.loads
import json

print(json.loads(request.data['all_letters']))

8 Comments

try to print(request.POST) what you get ? show me
<QueryDict: {'all_letters[]': ['a', 'b', 'c']}>
@TaohidulIslam i make and update try something like this
maybe django convert it automatically ?
request.data.get("all_letters") gives ["A","B","C"] and json.loads(request.data.get("all_letters")) gives ['A','B','C'] !
|
0

Try 'all_letter[]' as key just like below:

request.data["all_letters[]"]

This might work otherwise try to construct querydict properly in JS code and try to access it.

1 Comment

It shows django.utils.datastructures.MultiValueDictKeyError: 'all_letters '

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.