Просмотр исходного кода

Raise a validation error if remove_tags is specified when creating an object

Jeremy Stretch 3 дней назад
Родитель
Сommit
8bc691099c
2 измененных файлов с 26 добавлено и 0 удалено
  1. 21 0
      netbox/dcim/tests/test_api.py
  2. 5 0
      netbox/netbox/api/serializers/features.py

+ 21 - 0
netbox/dcim/tests/test_api.py

@@ -368,6 +368,27 @@ class SiteTest(APIViewTestCases.APIViewTestCase):
         tag_names = sorted(site.tags.values_list('name', flat=True))
         self.assertEqual(tag_names, ['Alpha', 'Bravo'])
 
+    def test_create_with_remove_tags_error(self):
+        """
+        Using remove_tags when creating a new object should raise a validation error.
+        """
+        Tag.objects.bulk_create((
+            Tag(name='Alpha', slug='alpha'),
+        ))
+
+        obj_perm = ObjectPermission(name='Test permission', actions=['add'])
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(self.model))
+
+        data = {
+            'name': 'Site 10',
+            'slug': 'site-10',
+            'remove_tags': [{'name': 'Alpha'}],
+        }
+        response = self.client.post(self._get_list_url(), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
+
 
 class LocationTest(APIViewTestCases.APIViewTestCase):
     model = Location

+ 5 - 0
netbox/netbox/api/serializers/features.py

@@ -55,6 +55,11 @@ class TaggableModelSerializer(serializers.Serializer):
                 'tags': 'Cannot specify "tags" together with "add_tags" or "remove_tags".'
             })
 
+        if self.instance is None and data.get('remove_tags'):
+            raise serializers.ValidationError({
+                'remove_tags': 'Cannot use "remove_tags" when creating a new object.'
+            })
+
         # Pop add_tags/remove_tags before calling super() to prevent them from being passed
         # to the model constructor during ValidatedModelSerializer validation
         add_tags = data.pop('add_tags', None)