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

12 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-22 07:51 +0000

1from django.core.exceptions import ValidationError 

2from django.forms import ModelChoiceField 

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)