Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/polymorphic/admin/filters.py: 37%

19 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1from django.contrib import admin 

2from django.core.exceptions import PermissionDenied 

3from django.utils.translation import gettext_lazy as _ 

4 

5 

6class PolymorphicChildModelFilter(admin.SimpleListFilter): 

7 """ 

8 An admin list filter for the PolymorphicParentModelAdmin which enables 

9 filtering by its child models. 

10 

11 This can be used in the parent admin: 

12 

13 .. code-block:: python 

14 

15 list_filter = (PolymorphicChildModelFilter,) 

16 """ 

17 

18 title = _("Type") 

19 parameter_name = "polymorphic_ctype" 

20 

21 def lookups(self, request, model_admin): 

22 return model_admin.get_child_type_choices(request, "change") 

23 

24 def queryset(self, request, queryset): 

25 try: 

26 value = int(self.value()) 

27 except TypeError: 

28 value = None 

29 if value: 

30 # ensure the content type is allowed 

31 for choice_value, _ in self.lookup_choices: 

32 if choice_value == value: 

33 return queryset.filter(polymorphic_ctype_id=choice_value) 

34 raise PermissionDenied( 

35 'Invalid ContentType "{}". It must be registered as child model.'.format(value) 

36 ) 

37 return queryset