Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django equivalent of PHP's form value array/associative array

In PHP, I would do this to get name as an array.

<input type"text" name="name[]" /> <input type"text" name="name[]" /> 

Or if I wanted to get name as an associative array:

<input type"text" name="name[first]" /> <input type"text" name="name[last]" /> 

What is the Django equivalent for such things?

like image 483
Imran Avatar asked Apr 29 '09 08:04

Imran


People also ask

Is $_ POST an associative array?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.

Are PHP associative arrays ordered?

So yes, they are always ordered. Arrays are implemented as a hash table.

What is a PHP associative array?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.

What is associative array in PHP explain with an example program?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.


1 Answers

Check out the QueryDict documentation, particularly the usage of QueryDict.getlist(key).

Since request.POST and request.GET in the view are instances of QueryDict, you could do this:

<form action='/my/path/' method='POST'> <input type='text' name='hi' value='heya1'> <input type='text' name='hi' value='heya2'> <input type='submit' value='Go'> </form> 

Then something like this:

def mypath(request):     if request.method == 'POST':         greetings = request.POST.getlist('hi') # will be ['heya1','heya2'] 
like image 90
Paolo Bergantino Avatar answered Oct 01 '22 02:10

Paolo Bergantino