views:

1770

answers:

2

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?

+17  A: 

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']
Paolo Bergantino
+2  A: 

Django does not provide a way to get associative arrays (dictionaries in Python) from the request object. As the first answer pointed out, you can use .getlist() as needed, or write a function that can take a QueryDict and reorganize it to your liking (pulling out key/value pairs if the key matches some key[*] pattern, for example).

Grant