Created
October 26, 2017 16:39
-
-
Save bmispelon/98f486dbc6208ee65b9ba79440f10adf to your computer and use it in GitHub Desktop.
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
| from django.forms.widgets import MultiWidget | |
| def form_to_POST(form): | |
| """ | |
| Given a form, convert its initial data into a dict that can simulate | |
| the request.POST that would be generated if that form was submitted as-is. | |
| This will respect the form's prefix and will convert all field values to | |
| strings. | |
| """ | |
| data = {} | |
| for boundfield in form: | |
| value = boundfield.value() | |
| widget = boundfield.field.widget | |
| if not isinstance(widget, MultiWidget): | |
| data[boundfield.html_name] = value | |
| else: | |
| # For MultiWidget, things get a bit more complicated because | |
| # we need to add several keys to the `data` dict. | |
| # Unfortunately, the MultiWidget class doesn't provide many useful | |
| # hooks to split a value into its subwidget-specific components | |
| # so we end up copy/pasting most of the logic from MultiWidget.render() | |
| # here. | |
| decompressed_value = widget.decompress(value) | |
| for i, (widget, widget_value) in enumerate(zip(widget.widgets, decompressed_value)): | |
| subwidget_name = '{}_{}'.format(boundfield.html_name, i) | |
| data[subwidget_name] = widget_value | |
| return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment