Ivan Smirnov
Ivan Smirnov

Reputation: 53

Can't correctly receive data in Django from Ajax

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?

Upvotes: 1

Views: 273

Answers (3)

rodp63
rodp63

Reputation: 1

You can add the parameter traditional: true to your ajax request. Which forces to use the traditional style of param serialization, getting rid of the square brackets in the query keys.

var arr = [1, 2];
$.ajax({
    type: 'POST',
    url: '/go/',
    data: {arr: arr},
    traditional: true,
    success: function (data) {
    console.log('Success!');
    },
});

Upvotes: 0

Chymdy
Chymdy

Reputation: 660

You are passing a list, and so will need to use the getlist method to retrieve the data.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

The name of the key is 'arr[]', since it contains an array, so you access this with:

def go(request):
  if request.method == 'POST':
    arr = request.POST.getlist('arr[]')

You need to use .getlist(…) [Django-doc] to retrieve all values, since the different elements are all passed as individual key-value items.

Upvotes: 1

Related Questions