mirror of
https://github.com/netbox-community/netbox.git
synced 2025-12-23 21:57:47 -06:00
Introduce CSVModelForm for dynamic CSV imports
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user