Skip to content

Instantly share code, notes, and snippets.

@ijharulislam
Forked from MasterAlish/html_input_dict.py
Created August 10, 2018 11:53
Show Gist options
  • Save ijharulislam/28e9743e68a165dff0e4d1669644c4ba to your computer and use it in GitHub Desktop.
Save ijharulislam/28e9743e68a165dff0e4d1669644c4ba to your computer and use it in GitHub Desktop.
Django html input array and dict
def get_html_input_dict(self, query_dict, param):
dictionary = {}
regex = re.compile('%s\[([\w\d_]+)\]' % param)
for key, value in query_dict.items():
match = regex.match(key)
if match:
inner_key = match.group(1)
dictionary[inner_key] = value
return dictionary
# query_dict - request.POST or request.GET
# param - html parameter name
#
# Use example:
# <form method="post">
# <input type='text' name='student[1]'>
# <input type='text' name='student[2]'>
# <input type='text' name='student[3]'>
# ...
# </form>
#
# In django views do next:
# students = get_html_input_dict(request.POST, 'student')
#
# It returns:
# students => {'1': ... , '2': ..., '3': ...}
@pboissonneault
Copy link

Great solution !
I've updated your code to get multi-dimentionnal arrays :

def get_html_input_dict(query_dict, param):
    dictionary = {}
    regex = re.compile('%s\[([\w\d_]+)\]' % param)
    for key, value in query_dict.items():
        match = regex.match(key)
        if match:
            inner_key = match.group(1)
            regex_sec = re.compile('%s\[%s\]\[([\w\d_]+)\]' % (param, inner_key))
            match_second = regex_sec.match(key)
            if match_second:
                dictionary[inner_key] = get_html_input_dict(query_dict, '%s\[%s\]' % (param, inner_key))
            else:
                dictionary[inner_key] = value

    return dictionary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment