Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #11617: Check for invalid CSV headers during bulk import #13826

Merged
merged 2 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions netbox/utilities/forms/bulk_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ def _clean_csv(self, data, delimiter=CSVDelimiterChoices.AUTO):
headers, records = parse_csv(reader)

# Set CSV headers for reference by the model form
headers.pop('id', None)
self._csv_headers = headers

return records
Expand Down
22 changes: 12 additions & 10 deletions netbox/utilities/forms/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,24 @@ class CSVModelForm(forms.ModelForm):
"""
ModelForm used for the import of objects in CSV format.
"""
def __init__(self, *args, headers=None, fields=None, **kwargs):
headers = headers or {}
fields = fields or []
def __init__(self, *args, headers=None, **kwargs):
self.headers = headers or {}
super().__init__(*args, **kwargs)

# Modify the model form to accommodate any customized to_field_name properties
for field, to_field in headers.items():
for field, to_field in self.headers.items():
if to_field is not None:
self.fields[field].to_field_name = to_field

# Omit any fields not specified (e.g. because the form is being used to
# updated rather than create objects)
if fields:
for field in list(self.fields.keys()):
if field not in fields:
del self.fields[field]
def clean(self):
# Flag any invalid CSV headers
for header in self.headers:
if header not in self.fields:
raise forms.ValidationError(
_("Unrecognized header: {name}").format(name=header)
)

return super().clean()


class FilterForm(BootstrapMixin, forms.Form):
Expand Down
Loading