request.POST.getlist('xxx') only has one value in ajax request for many2many

52 views
Skip to first unread message

Campbell McKilligan

unread,
Jan 16, 2022, 3:30:01 PM1/16/22
to Django users
Hi,

Using Django 3.2 and Py 3.9

I have an ajax request which submits multiple values for a field to an UpdateView.

In the request dict body I see both values (in this case, for the pool_list column):

'_body': b"csrfmiddlewaretoken=z...h&...&key=...&expiry_datetime=&overflow=555&pool_list=507&pool_list=499&...

Later in the request dict, I only see one of the values in the _post:
'_post': .... 'pool_list': ['499'],

This means that in request.POST.getlist('pool_list'), I'm only getting one result in the list object.

Any idea why it's only the last value being populated in the getlist?

Odigiri Richard

unread,
Jan 16, 2022, 5:42:45 PM1/16/22
to django...@googlegroups.com
You might want to loop through the list 
Example:
Lists = request.getlist('item')
For list in Lists:
.........


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bf3a5e3b-4e8c-4a73-8647-d494bedbdf90n%40googlegroups.com.

Jason

unread,
Jan 16, 2022, 8:34:18 PM1/16/22
to Django users
https://code.djangoproject.com/ticket/1130

Essentially, this is expected behavior, and previous comment is correct.  Need to loop through the items in the list

Campbell McKilligan

unread,
Jan 17, 2022, 12:51:36 PM1/17/22
to Django users
Yeah - I am looping.  I just get one iteration which is the last item even though the request body has the same key repeated.

For example, this code only prints one item, whereas for a different form elsewhere, it would iterate through all the identical keys:
       print(self.request.__dict__)
      for pool in self.request.POST.getlist('pool_list'):
      print(f"form pool_list item: {pool}")

The main difference to when it works is that this form is submitted via ajax; and uses UpdateView.

Julio Cojom

unread,
Jan 17, 2022, 1:07:49 PM1/17/22
to django...@googlegroups.com
I remember having a problem like that once, in your views print the hole dictionary "print(request.POST)", you should see all the values of the field you want as list, not just one.

Then instead of getlist try just get, request.POST.get('field_here')

Let me know how it goes 

Reply all
Reply to author
Forward
0 new messages