54

When I try to send an array to Django via Ajax (jQuery)

JavaScript code:

new_data = ['a','b','c','d','e'];
$.get('/pythonPage/', {'data': new_data},function(data){});

and I try to read the array:

Python:

request.GET.get("data[]")

I get only the last array value:

'e'

What am I doing wrong?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Erez
  • 2,615
  • 2
  • 21
  • 27

4 Answers4

106

You're looking for the QueryDict's getlist

request.GET.getlist('data')
request.GET.getlist('data[]')
request.GET.getlist('etc')

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict.getlist

Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 45
    Had a similar problem but using the `POST` method, where the final line that worked for me was `request.POST.getlist('data[]')` – yellowcap Feb 14 '13 at 09:16
  • 1
    `'selected = request.GET.getlist['selected[]'] TypeError: 'instancemethod' object has no attribute '__getitem__'` I get this error... But i have an array of stings like ["one","two","three"] – nidHi Aug 17 '16 at 04:57
  • 2
    @nidHi you need `request.GET.getlist('selected[]')` instead of `request.GET.getlist['selected[]']` – DDS Jan 27 '17 at 17:49
  • request.GET.getlist('data[]') worked for me in Django 2.0 – Akhilendra Feb 21 '18 at 07:09
  • I owe you one mate, i was looking for this and it was driving me crazy – ascoder May 04 '20 at 18:15
  • not in django but in wsgi I had to extract my ajax list data (with keys) somehow, so I managed to loop through the data list (stripe products) via the count that was passed in as well... then doing something like productid = post.getvalue("productlist[0][id]") – Lenn Dolling Aug 25 '22 at 02:27
6

Quite old question but let me show you full working code for this. (Good for newbie :)

In your template

data = {
    'pk' : [1,3,5,10]
}

$.post("{% url 'yourUrlName' %}", data, 
    function(response){
        if (response.status == 'ok') {
            // It's all good
            console.log(response)
        } else {
            // Do something with errors
        }
    })

urls.py

urlpatterns = [
    url(r'^yourUrlName/', views.yourUrlName, name='yourUrlName'), #Ajax
]

views.py

from django.views.decorators.http import require_POST
from django.http import JsonResponse


@require_POST
def yourUrlName(request):
    array = request.POST.getlist('pk[]')

    return JsonResponse({
            'status':'ok',
            'array': array,
        })
Michael Stachura
  • 1,100
  • 13
  • 18
2

Just use request.GET.getlist('data[]')

1

With newer versions of django I was finding that even @YellowCap suggestion of request.POST.getlist('data[]') wasn't working for me.

However dict(request.POST)["data"] does work. Context here: https://code.djangoproject.com/ticket/1130

William
  • 171
  • 1
  • 12