request.POST get multiple values

Posted: February 24th, 2010 | Author: | Filed under: Django | Tags: , , | 7 Comments »

The QueryDict.getlist() allows to get all the checkbox(or select list) values from the request.POST/GET object.

Let’s assume we have a simple form with the following checkboxes. Each checkbox contains an ID of an artist.


... ...

In views.py :

def handle(request):
    if request.method == 'POST':
         artists = request.POST.getlist('artists') # now artists is a list of [1,2,3]

7 Comments on “request.POST get multiple values”

  1. 1 Panchicore said at 1:21 am on March 2nd, 2010:

    @Davo
    Thats was totally #$%& usefull for me :) Thanks.

  2. 2 SpiegS said at 9:06 pm on March 10th, 2010:

    I have a question – what would be the best way in the case of GET (form with action GET) to convert the list back to a proper URL? urlencode doesn’t work – it converts the list to string ‘[1,2,3]‘ which in turn is’nt recognized properly by getlist anymore.

  3. 3 Davo said at 10:14 pm on March 10th, 2010:

    Hello SpiegS,

    What you can do is the following:

    >>> from django.http import QueryDict
    >>> q = QueryDict(‘artists=1′).copy()
    >>> my_artists = [11,22,33,44]
    >>> q.setlist(‘artists’, my_artists)
    >>> print q
    <QueryDict: {u’artists’: [11, 22, 33, 44]}>
    >>> print q.urlencode()
    artists=11&artists=22&artists=33&artists=44

    Hope this helps.

  4. 4 SpiegS said at 4:20 pm on March 11th, 2010:

    Thx. Didn’t knew this.

  5. 5 Larry said at 2:28 am on December 4th, 2010:

    you learn something everyday..
    thanks a lot

  6. 6 Janne said at 11:04 am on August 4th, 2011:

    Thank you! Just what i was looking for.

  7. 7 akshar said at 12:37 pm on October 3rd, 2011:

    thanks a lot, i was looking for it. saved me some time.