Django equivalent of an array of PHP form values ​​/ 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?

+44
python django html-form forms
Apr 29 '09 at 8:04
source share
3 answers

Check out the QueryDict documentation , especially using QueryDict.getlist(key) .

Since request.POST and request.GET in the view are instances of QueryDict, you can 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'] 
+60
Apr 29 '09 at 12:03
source share

Sorry for that, but Django has utils.datastructures.DotExpandedDict. Here is part of this document:

 >>> 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 is the use of periods instead of brackets. I think that now it is conceptually replaced by prefix forms in form sets, but the class remains in the code base.

+18
Jan 20 2018-11-11T00:
source share

Django does not provide a way to get associative arrays (dictionaries in Python) from a request object. As pointed out in the first answer, 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 kind of key[*] pattern for example) .

+5
Apr 29 '09 at 23:40
source share



All Articles