Coverage for apis_core/generic/templatetags/generic.py: 43%

49 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-20 09:24 +0000

1from django import template 

2from django.contrib.contenttypes.models import ContentType 

3 

4from apis_core.core.templatetags.core import get_model_fields 

5from apis_core.generic.abc import GenericModel 

6from apis_core.generic.helpers import template_names_via_mro 

7 

8register = template.Library() 

9 

10 

11@register.filter 

12def contenttype(model): 

13 return ContentType.objects.get_for_model(model) 

14 

15 

16@register.simple_tag 

17def modeldict(instance, fields=None, exclude=None): 

18 data = {} 

19 for f in get_model_fields(instance): 

20 if not getattr(f, "editable", False): 

21 continue 

22 if fields is not None and f.name not in fields: 

23 continue 

24 if exclude and f.name in exclude: 

25 continue 

26 field = instance._meta.get_field(f.name) 

27 data[field] = instance._get_FIELD_display(field) 

28 if getattr(field, "remote_field", False): 

29 data[field] = getattr(instance, field.name) 

30 if getattr(field, "m2m_field_name", False): 

31 values = getattr(instance, field.name).all() 

32 data[field] = ", ".join([str(value) for value in values]) 

33 return data 

34 

35 

36@register.simple_tag 

37def contenttypes(app_labels=None): 

38 if app_labels: 

39 app_labels = app_labels.split(",") 

40 return ContentType.objects.filter(app_label__in=app_labels) 

41 return ContentType.objects.all() 

42 

43 

44def is_genericmodel(content_type: ContentType): 

45 model_class = content_type.model_class() 

46 return model_class is not None and issubclass(model_class, GenericModel) 

47 

48 

49@register.simple_tag 

50def genericmodel_content_types(): 

51 """ 

52 Retrieve all models which inherit from GenericModel class 

53 and return their ContentType. 

54 """ 

55 genericmodels = list( 

56 filter( 

57 lambda content_type: is_genericmodel(content_type), 

58 ContentType.objects.all(), 

59 ) 

60 ) 

61 return genericmodels 

62 

63 

64@register.filter 

65def get_attribute(obj, attribute): 

66 return getattr(obj, attribute, None) 

67 

68 

69@register.filter 

70def content_type_count(content_type): 

71 """ 

72 Return the number of objects having a specific content type 

73 """ 

74 return content_type.model_class().objects.count() 

75 

76 

77@register.simple_tag 

78def template_list(obj, suffix): 

79 return template_names_via_mro(type(obj), suffix)