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

45 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-22 07:51 +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 

6 

7register = template.Library() 

8 

9 

10@register.filter 

11def contenttype(model): 

12 return ContentType.objects.get_for_model(model) 

13 

14 

15@register.simple_tag 

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

17 data = {} 

18 for f in get_model_fields(instance): 

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

20 continue 

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

22 continue 

23 if exclude and f.name in exclude: 

24 continue 

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

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

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

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

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

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

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

32 return data 

33 

34 

35@register.simple_tag 

36def contenttypes(app_labels=None): 

37 if app_labels: 

38 app_labels = app_labels.split(",") 

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

40 return ContentType.objects.all() 

41 

42 

43def is_genericmodel(content_type: ContentType): 

44 model_class = content_type.model_class() 

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

46 

47 

48@register.simple_tag 

49def genericmodel_content_types(): 

50 """ 

51 Retrieve all models which inherit from GenericModel class 

52 and return their ContentType. 

53 """ 

54 genericmodels = list( 

55 filter( 

56 lambda content_type: is_genericmodel(content_type), 

57 ContentType.objects.all(), 

58 ) 

59 ) 

60 return genericmodels 

61 

62 

63@register.filter 

64def get_attribute(obj, attribute): 

65 return getattr(obj, attribute, None) 

66 

67 

68@register.filter 

69def content_type_count(content_type): 

70 """ 

71 Return the number of objects having a specific content type 

72 """ 

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