Created
June 4, 2018 07:57
-
-
Save martin056/251f9cb160368674569dcd18b7bd3a40 to your computer and use it in GitHub Desktop.
Transforms form data with initial values to a dictionary that can be used for POST request. Handles Django admin forms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def form_soup_to_dict(form_soup, add_save=False): | |
""" | |
Transforms form data with initial values to a dictionary that can be used for POST request. | |
* `add_save` - In Django Admin forms POST data expects `_save` to make the request. | |
""" | |
data = {} | |
for input_field in form_soup.find_all('input'): | |
# We have some custom buttons added to the Django Admin | |
if input_field['type'] in ('hidden', 'submit'): | |
continue | |
# Django Admin specific fields | |
if input_field.attrs['name'].startswith('_'): | |
continue | |
if input_field.attrs['type'] == 'checkbox': | |
if input_field.has_attr('checked'): | |
data[input_field.attrs['name']] = 'on' | |
continue | |
data[input_field.attrs['name']] = input_field.attrs.get('value') | |
for select_field in form_soup.find_all('select'): | |
multiple_input = [] | |
if select_field.has_attr('multiple'): | |
for opt in select_field.find_all('option'): | |
if opt.has_attr('selected'): | |
multiple_input.append(opt['value']) | |
if len(multiple_input) > 0: | |
data[select_field['name']] = multiple_input | |
continue | |
for opt in select_field.find_all('option'): | |
if opt.has_attr('selected'): | |
data[select_field['name']] = opt['value'] | |
for textarea in form_soup.find_all('textarea'): | |
data[textarea['name']] = textarea.string | |
if add_save: | |
data['_save'] = 'Save' | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment