From 4433befbdc0c51cea2f35610d3f5f267c0f77ad6 Mon Sep 17 00:00:00 2001 From: Oliver Date: Tue, 9 Nov 2021 17:19:12 +1100 Subject: [PATCH] Add list of 'choices' (read only) to serializer - Check that the specified value is one of the valid options (if provided) --- InvenTree/common/models.py | 18 ++++++++++++++++++ InvenTree/common/serializers.py | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/InvenTree/common/models.py b/InvenTree/common/models.py index 43de6767bd..a941499f7e 100644 --- a/InvenTree/common/models.py +++ b/InvenTree/common/models.py @@ -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 diff --git a/InvenTree/common/serializers.py b/InvenTree/common/serializers.py index 85908872f8..ed120917cf 100644 --- a/InvenTree/common/serializers.py +++ b/InvenTree/common/serializers.py @@ -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', ]