skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You are passing a list, and so will need to use the getlist method to retrieve the data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search