Coverage for apis_core/generic/forms/fields.py: 54%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-02-19 16:54 +0000

1from django.core.exceptions import ValidationError 

2from django.forms import ChoiceField, ModelChoiceField, MultiValueField, MultiWidget 

3from django.utils.translation import gettext as _ 

4 

5from apis_core.utils.helpers import create_object_from_uri 

6 

7 

8class ModelImportChoiceField(ModelChoiceField): 

9 def to_python(self, value): 

10 result = None 

11 try: 

12 result = create_object_from_uri(value, self.queryset.model) 

13 except Exception as e: 

14 raise ValidationError( 

15 _("Could not import %(value)s: %(exception)s"), 

16 params={"value": value, "exception": e}, 

17 ) 

18 return result or super().to_python(value) 

19 

20 

21class IncludeExcludeMultiWidget(MultiWidget): 

22 template_name = "widgets/includeexclude_multiwidget.html" 

23 use_fieldset = False 

24 

25 def decompress(self, value): 

26 return [value, value] 

27 

28 

29class IncludeExcludeField(MultiValueField): 

30 """ 

31 This is a custom MultiValueField that adds a ChoiceField that only provides two 

32 choices, namely `exclude` and `include`. It can be used for django-filter filters 

33 to specify which action should be done with the filter. 

34 """ 

35 

36 def __init__(self, field, *args, **kwargs): 

37 fields = ( 

38 field, 

39 ChoiceField(choices=[("include", "include"), ("exclude", "exclude")]), 

40 ) 

41 kwargs["widget"] = IncludeExcludeMultiWidget(widgets=[f.widget for f in fields]) 

42 super().__init__(fields=fields, *args, **kwargs) 

43 

44 def compress(self, data_list): 

45 return data_list