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

24 statements  

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

1from django.contrib.contenttypes.admin import GenericInlineModelAdmin 

2from django.contrib.contenttypes.models import ContentType 

3from django.utils.functional import cached_property 

4 

5from polymorphic.formsets import ( 

6 BaseGenericPolymorphicInlineFormSet, 

7 GenericPolymorphicFormSetChild, 

8 polymorphic_child_forms_factory, 

9) 

10 

11from .inlines import PolymorphicInlineModelAdmin 

12 

13 

14class GenericPolymorphicInlineModelAdmin(PolymorphicInlineModelAdmin, GenericInlineModelAdmin): 

15 """ 

16 Base class for variation of inlines based on generic foreign keys. 

17 """ 

18 

19 #: The formset class 

20 formset = BaseGenericPolymorphicInlineFormSet 

21 

22 def get_formset(self, request, obj=None, **kwargs): 

23 """ 

24 Construct the generic inline formset class. 

25 """ 

26 # Construct the FormSet class. This is almost the same as parent version, 

27 # except that a different super is called so generic_inlineformset_factory() is used. 

28 # NOTE that generic_inlineformset_factory() also makes sure the GFK fields are excluded in the form. 

29 FormSet = GenericInlineModelAdmin.get_formset(self, request, obj=obj, **kwargs) 

30 

31 FormSet.child_forms = polymorphic_child_forms_factory( 

32 formset_children=self.get_formset_children(request, obj=obj) 

33 ) 

34 return FormSet 

35 

36 class Child(PolymorphicInlineModelAdmin.Child): 

37 """ 

38 Variation for generic inlines. 

39 """ 

40 

41 # Make sure that the GFK fields are excluded from the child forms 

42 formset_child = GenericPolymorphicFormSetChild 

43 ct_field = "content_type" 

44 ct_fk_field = "object_id" 

45 

46 @cached_property 

47 def content_type(self): 

48 """ 

49 Expose the ContentType that the child relates to. 

50 This can be used for the ``polymorphic_ctype`` field. 

51 """ 

52 return ContentType.objects.get_for_model(self.model, for_concrete_model=False) 

53 

54 def get_formset_child(self, request, obj=None, **kwargs): 

55 # Similar to GenericInlineModelAdmin.get_formset(), 

56 # make sure the GFK is automatically excluded from the form 

57 defaults = {"ct_field": self.ct_field, "fk_field": self.ct_fk_field} 

58 defaults.update(kwargs) 

59 return super(GenericPolymorphicInlineModelAdmin.Child, self).get_formset_child( 

60 request, obj=obj, **defaults 

61 ) 

62 

63 

64class GenericStackedPolymorphicInline(GenericPolymorphicInlineModelAdmin): 

65 """ 

66 The stacked layout for generic inlines. 

67 """ 

68 

69 #: The default template to use. 

70 template = "admin/polymorphic/edit_inline/stacked.html"