46

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?

3 Answers 3

64

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']
Sign up to request clarification or add additional context in comments.

1 Comment

This fails when key is important. For example name="question[4]" where 4 is question id.
18

Sorry for digging this up, but Django has an utils.datastructures.DotExpandedDict. Here's a piece of it's docs:

>>> d = DotExpandedDict({'person.1.firstname': ['Simon'], \
        'person.1.lastname': ['Willison'], \
        'person.2.firstname': ['Adrian'], \
        'person.2.lastname': ['Holovaty']})
>>> d
{'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}}

The only difference being you use dot's instead of brackets.

EDIT: This mechanism was replaced by form prefixes, but here's the old code you can drop in your app if you still want to use this concept: https://gist.github.com/grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60

6 Comments

This is the best solution I have found. Thx.
I rely on DotExpandedDict in my Django apps, and it is far more useful than QueryDict.getlist. Unfortunately, it has been removed from Django (at least the development version). You can still grab the source code for it, though.
DotExpandedDict is removed since django 1.5
Any ideas for a good replacement, since DotExpandedDict is removed?
@gzy how to actually replace it with form prefixes? I dont get it
|
5

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.