Last active
December 7, 2017 03:51
-
-
Save bhavaniravi/ba25500f252244c900710b303334c210 to your computer and use it in GitHub Desktop.
Creates formset data to replicate data posted by Django forms. This helps to generate data while writing test cases
This file contains 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 instantiate_formset_data(formset_class, data, instances=[], initial=None, action="add"): | |
""" | |
Input: | |
Formset_class | |
data - Python Dict type form data | |
Instances - [] if its a CreateForm, or list of instances in case of EditForm | |
Initial - Initial data if any | |
Action = define edit/Add action | |
Output: data --> Formset style Data | |
""" | |
prefix = formset_class().prefix | |
formset_data = {} | |
for i, instance in enumerate(instances): | |
formset_data['{}-{}-{}'.format(prefix, i, "id")] = [instance.id] | |
if not instances: | |
formset_data['{}-{}-{}'.format(prefix, 0, "id")] = [""] | |
for i, form_data in enumerate(data): | |
for name, value in form_data.items(): | |
formset_data['{}-{}-{}'.format(prefix, i, name)] = value | |
formset_data['{}-TOTAL_FORMS'.format(prefix)] = len(data) | |
formset_data['{}-INITIAL_FORMS'.format(prefix)] = 1 if action == "edit" else 0 | |
return formset_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment