Add list of 'choices' (read only) to serializer

- Check that the specified value is one of the valid options (if provided)
This commit is contained in:
Oliver 2021-11-09 17:19:12 +11:00
parent 07851f0b2c
commit 4433befbdc
2 changed files with 38 additions and 0 deletions

View File

@ -353,6 +353,11 @@ class BaseInvenTreeSetting(models.Model):
except (ValueError):
raise ValidationError(_('Must be an integer value'))
options = self.valid_options()
if options and self.value not in options:
raise ValidationError(_("Chosen value is not a valid option"))
if validator is not None:
self.run_validator(validator)
@ -419,6 +424,19 @@ class BaseInvenTreeSetting(models.Model):
return self.__class__.get_setting_choices(self.key)
def valid_options(self):
"""
Return a list of valid options for this setting
"""
choices = self.choices()
if not choices:
return None
return [opt[0] for opt in choices]
def is_bool(self):
"""
Check if this setting is required to be a boolean value

View File

@ -24,6 +24,15 @@ class GlobalSettingsSerializer(InvenTreeModelSerializer):
type = serializers.CharField(source='setting_type', read_only=True)
choices = serializers.SerializerMethodField()
def get_choices(self, obj: InvenTreeUserSetting):
"""
Returns the choices available for a given item
"""
return obj.choices()
class Meta:
model = InvenTreeSetting
fields = [
@ -33,6 +42,7 @@ class GlobalSettingsSerializer(InvenTreeModelSerializer):
'name',
'description',
'type',
'choices',
]
@ -51,6 +61,15 @@ class UserSettingsSerializer(InvenTreeModelSerializer):
type = serializers.CharField(source='setting_type', read_only=True)
choices = serializers.SerializerMethodField()
def get_choices(self, obj: InvenTreeUserSetting):
"""
Returns the choices available for a given item
"""
return obj.choices()
class Meta:
model = InvenTreeUserSetting
fields = [
@ -61,4 +80,5 @@ class UserSettingsSerializer(InvenTreeModelSerializer):
'description',
'user',
'type',
'choices',
]