I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it.
This is the piece of js code:
var arr = [1, 2];
$.ajax({
type: 'POST',
url: '/go/',
data: {arr: arr},
success: function (data) {
console.log('Success!');
},
});
And this is from Django view:
def go(request):
if request.method == 'POST':
arr = request.POST['arr']
It gives me KeyError: 'arr'
If I do print(request.POST)
in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>
. Some square brackets appear after ‘arr’ key. Then if I do arr = request.POST['arr[]']
using the key with square brackets it assings arr
value 2
, so only the last value of the array. Can someone please explain to me why this is happening?
2
Answers
The name of the key is
'arr[]'
, since it contains an array, so you access this with:You need to use
.getlist(…)
[Django-doc] to retrieve all values, since the different elements are all passed as individual key-value items.You are passing a list, and so will need to use the getlist method to retrieve the data.