1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Introduce CSVModelChoiceField to provide better validation for CSV model choices

This commit is contained in:
Jeremy Stretch
2020-05-06 09:43:10 -04:00
parent 607744813a
commit 70d0a5f665
7 changed files with 113 additions and 99 deletions

View File

@@ -8,6 +8,7 @@ import yaml
from django import forms
from django.conf import settings
from django.contrib.postgres.forms.jsonb import JSONField as _JSONField, InvalidJSONInput
from django.core.exceptions import MultipleObjectsReturned
from django.db.models import Count
from django.forms import BoundField
from django.forms.models import fields_for_model
@@ -481,7 +482,6 @@ class CSVChoiceField(forms.ChoiceField):
"""
Invert the provided set of choices to take the human-friendly label as input, and return the database value.
"""
def __init__(self, choices, *args, **kwargs):
super().__init__(choices=choices, *args, **kwargs)
self.choices = [(label, label) for value, label in unpack_grouped_choices(choices)]
@@ -496,6 +496,19 @@ class CSVChoiceField(forms.ChoiceField):
return self.choice_values[value]
class CSVModelChoiceField(forms.ModelChoiceField):
"""
Provides additional validation for model choices entered as CSV data.
"""
def to_python(self, value):
try:
return super().to_python(value)
except MultipleObjectsReturned as e:
raise forms.ValidationError(
f'"{value}" is not a unique value for this field; multiple objects were found'
)
class ExpandableNameField(forms.CharField):
"""
A field which allows for numeric range expansion