Introduce CSVModelForm for dynamic CSV imports

This commit is contained in:
Jeremy Stretch
2020-05-05 16:15:09 -04:00
parent d85d963842
commit 839e999a71
12 changed files with 280 additions and 294 deletions

View File

@@ -712,6 +712,20 @@ class BulkEditForm(forms.Form):
self.nullable_fields = self.Meta.nullable_fields
class CSVModelForm(forms.ModelForm):
"""
ModelForm used for the import of objects in CSV format.
"""
def __init__(self, *args, headers=None, **kwargs):
super().__init__(*args, **kwargs)
# Modify the model form to accommodate any customized to_field_name properties
if headers:
for field, to_field in headers.items():
if to_field is not None:
self.fields[field].to_field_name = to_field
class ImportForm(BootstrapMixin, forms.Form):
"""
Generic form for creating an object from JSON/YAML data

View File

@@ -593,12 +593,7 @@ class BulkImportView(GetReturnURLMixin, View):
with transaction.atomic():
headers, records = form.cleaned_data['csv']
for row, data in enumerate(records, start=1):
obj_form = self.model_form(data)
# Modify the model form to accommodate any customized to_field_name properties
for field, to_field in headers.items():
if to_field is not None:
obj_form.fields[field].to_field_name = to_field
obj_form = self.model_form(data, headers=headers)
if obj_form.is_valid():
obj = self._save_obj(obj_form, request)