Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble accessing HTML array input field values in Django server side

Tags:

html

django

For below input fields, I have an add button that duplicates the following input field so I can add multiple values of attributes. Here, the attributes are "color", "gender", and "size.

<tr>
    {% for att in attribute_set %}
        <td><input name="{{ att }}[]" class="form-control" placeholder="{{ att|title }}"></td>
    {% endfor %}
</tr>

For example: This renders as

<input name="color[]" class="form-control" placeholder="Color">

In the server side, this form on being submitted, gives a request.POST as below.

<QueryDict: {u'size[]': [u'asdasd', u'bla'], u'gender[]': [u'asdsda', u''], u'color[]': [u'adadas', u'67']>

Trying to access the array gives,

>> request.POST["color[]"]
>> u'67'
>> request.POST["size[]"]
>> u'bla'

Only the last value of the array is being returned. What am I doing wrong?

like image 940
hlkstuv_23900 Avatar asked Aug 31 '15 19:08

hlkstuv_23900


Video Answer


1 Answers

You need to use .getlist to get the whole list instead.

>>> request.POST.getlist("color[]")
[u'adadas', u'67']    
>>> request.POST.getlist("size[]")
[u'asdasd', u'bla']

Since request.POST is a QueryDict, it will return the last element on accessing a key having multiple values. You will have to use .getlist to get the complete value.

From QueryDict.__getitem__(key) documentation:

Returns the value for the given key. If the key has more than one value, __getitem__() returns the last value.

For example:

>>> q = QueryDict('a=1', mutable=True) # create a querydict instance
>>> q.update({'a': '2'}) # add multiple value for key 'a'

>>> q['a'] # access a key having multiple values
['2'] # returns the last value

>>> q.getlist('a') # use getlist 
['1', '2'] # returns complete value
like image 53
Rahul Gupta Avatar answered Nov 15 '22 07:11

Rahul Gupta