Coverage for website/pizzas/api/v2/admin/validators.py: 26.47%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2025-08-14 10:31 +0000

1from django.utils.translation import gettext_lazy as _ 

2 

3from rest_framework.exceptions import ValidationError 

4 

5 

6class MutuallyExclusiveValidator: 

7 """Validator that corresponds to `unique=True` on a model field. 

8 

9 Should be applied to an individual field on the serializer. 

10 """ 

11 

12 message = _("The fields {field_names} are mutually exclusive.") 

13 missing_message = _("This field is required.") 

14 requires_context = True 

15 

16 def __init__(self, fields): 

17 self.fields = fields 

18 

19 def __call__(self, attrs, serializer): 

20 sources = [serializer.fields[field_name].source for field_name in self.fields] 

21 

22 # If this is an update, then any unprovided field should 

23 # have it's value set based on the existing instance attribute. 

24 if serializer.instance is not None: 

25 for source in sources: 

26 if source not in attrs: 

27 attrs[source] = getattr(serializer.instance, source) 

28 

29 field_present = False 

30 for field in self.fields: 

31 if field in attrs and attrs[field] is not None: 

32 if field_present: 

33 field_names = ", ".join(self.fields) 

34 message = self.message.format(field_names=field_names) 

35 raise ValidationError(message, code="exclusive") 

36 field_present = True