Explorar o código

Fixes #2676: Fix exception when passing dictionary value to a ChoiceField

Jeremy Stretch %!s(int64=7) %!d(string=hai) anos
pai
achega
8364e56e86
Modificáronse 2 ficheiros con 19 adicións e 9 borrados
  1. 1 0
      CHANGELOG.md
  2. 18 9
      netbox/utilities/api.py

+ 1 - 0
CHANGELOG.md

@@ -3,6 +3,7 @@ v2.5.1 (FUTURE)
 ## Bug Fixes
 ## Bug Fixes
 
 
 * [#2666](https://github.com/digitalocean/netbox/issues/2666) - Correct display of length unit in cables list
 * [#2666](https://github.com/digitalocean/netbox/issues/2666) - Correct display of length unit in cables list
+* [#2676](https://github.com/digitalocean/netbox/issues/2676) - Fix exception when passing dictionary value to a ChoiceField
 
 
 ---
 ---
 
 

+ 18 - 9
netbox/utilities/api.py

@@ -78,17 +78,26 @@ class ChoiceField(Field):
         return data
         return data
 
 
     def to_internal_value(self, data):
     def to_internal_value(self, data):
+
+        # Provide an explicit error message if the request is trying to write a dict
+        if type(data) is dict:
+            raise ValidationError('Value must be passed directly (e.g. "foo": 123); do not use a dictionary.')
+
+        # Check for string representations of boolean/integer values
         if hasattr(data, 'lower'):
         if hasattr(data, 'lower'):
-            # Hotwiring boolean values from string
             if data.lower() == 'true':
             if data.lower() == 'true':
-                return True
-            if data.lower() == 'false':
-                return False
-            # Check for string representation of an integer (e.g. "123")
-            try:
-                data = int(data)
-            except ValueError:
-                pass
+                data = True
+            elif data.lower() == 'false':
+                data = False
+            else:
+                try:
+                    data = int(data)
+                except ValueError:
+                    pass
+
+        if data not in self._choices:
+            raise ValidationError("{} is not a valid choice.".format(data))
+
         return data
         return data