Skip to content Skip to sidebar Skip to footer

Django And Html Arrays

I have a form with this inputs: when I submit, h

Solution 1:

Sorry for answering such an old question, but i stuck with the same problem and didn't found any acceptable answers for it. 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')

Solution 2:

this doesn't seem like a very pythonic way to do it. or even a django-nic way to do it.

http://docs.djangoproject.com/en/dev/topics/forms/

I haven't really done a lot of forms stuff with django yet, but this looks like it would be helpful in terms of automatic generation, validation, etc.

Solution 3:

If you define your forms this way in templates, you cannot map it to a dictionary directly.

You should obtain individual values only

request.POST['person[name]']

However, this is no way to use forms in django. You should rather define these fields as per django form declarative syntax (docs), and let django handle the rendering in the templates using a tag like:

{{form.as_p}}
{{form.as_table}}

That way, you can define save method on the form class to perform your "array mapping" function. If you want to map it to a model defined, this comes stocked, and your form should extend ModelForm, to take that advantage.

Post a Comment for "Django And Html Arrays"