Django and HTML arrays
I have a form with these inputs:
<input name="person[name]" value="">
<input name="person[surname]" value="">
<input name="person[age]" value="">
when i post how can i assign this html array to a variable call request.POST.getlist ('person') doesn't work, i checked another entry but only one i found has nothing useful
I hope someone can help me figure this out, trigger the doc reading and do my best ...
The thing is, I have a table in my db with discounts ... where each discount has a default value ... so I did this
discounts = Discount.objects.all( )
{% for i in discounts %}
<input name="discount[{{ i.id }}]" value="{{ i.default_value }}">
{% endfor %}
and on mine i dont have any method to catch this html array i am posting ... any suggestions?
source to share
Sorry for answering such an old question, but I ran into the same problem and didn't find any acceptable answers. So here is my solution:
def get_post_dict(post, key):
result = {}
if post:
import re
patt = re.compile('^([a-zA-Z_]\w+)\[([a-zA-Z_\-][\w\-]*)\]$')
for post_name, value in post.items():
value = post[post_name]
match = patt.match(post_name)
if not match or not value:
continue
name = match.group(1)
if name == key:
k = match.group(2)
result.update({k:value})
return result
Now you can use it like this:
persons = get_post_dict(request.POST, 'person') ...
or
django.http.QueryDict.getdict = get_post_dict
persons = request.POST.getdict('person')
source to share
it doesn't seem like a very pythonic way to do it. or even the django-nic way to do it.
http://docs.djangoproject.com/en/dev/topics/forms/
I haven't done a lot of stuff with django yet, but it looks like it would be useful in terms of auto-generation, validation, etc.
source to share
If you define your forms this way in templates, you cannot directly match them to a dictionary.
You should only get individual values
request.POST['person[name]']
However, this is not the way to use forms in django. You have to define these fields according to django's declarative form syntax ( docs ), and let django handle rendering in templates using a tag like:
{{form.as_p}} {{form.as_table}}
Thus, you can define a method save
in the form class to execute your array mapping function. If you want to match it to a specific model, this will stock up and your form must expand ModelForm
to take advantage of this.
source to share