Coverage for apis_core/generic/tables.py: 76%
42 statements
« prev ^ index » next coverage.py v7.5.3, created at 2026-03-06 11:42 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2026-03-06 11:42 +0000
1import django_tables2 as tables
3from apis_core.generic.helpers import permission_fullname
6class CustomTemplateColumn(tables.TemplateColumn):
7 """
8 A custom template column - the `tables.TemplateColumn` class does not allow
9 to set attributes via class variables. Therefor we use this
10 CustomTemplateColumn to set some arguments based on class attributes and
11 override the attributes in child classes.
12 """
14 template_name = None
15 orderable = None
16 exclude_from_export = False
17 verbose_name = None
19 def __init__(self, *args, **kwargs):
20 super().__init__(
21 template_name=self.template_name,
22 orderable=self.orderable,
23 exclude_from_export=self.exclude_from_export,
24 verbose_name=self.verbose_name,
25 *args,
26 **kwargs,
27 )
30class ActionColumn(CustomTemplateColumn):
31 """
32 A custom template column with some additional attributes
33 for actions.
34 """
36 orderable = False
37 exclude_from_export = True
38 attrs = {"td": {"style": "width:1%;"}, "th": {"style": "font-size: 0"}}
40 def render(self, record, table, *args, **kwargs):
41 if permission := getattr(self, "permission", False):
42 if not table.request.user.has_perm(permission_fullname(permission, record)):
43 return ""
44 return super().render(record, table, *args, **kwargs)
47class ActionsColumn(CustomTemplateColumn):
48 orderable = False
49 exclude_from_export = True
50 template_name = "columns/actions.html"
51 attrs = {"td": {"style": "width:8em;"}, "th": {"style": "font-size: 0"}}
54class DescriptionColumn(CustomTemplateColumn):
55 """
56 A column showing a model description
57 """
59 template_name = "columns/description.html"
60 orderable = False
63class GenericTable(tables.Table):
64 """
65 A generic table that contains an edit button column, a delete button column
66 and a description column
67 """
69 desc = DescriptionColumn()
70 actions = ActionsColumn()
72 class Meta:
73 fields = ["id", "desc"]
74 sequence = ("...", "actions")
77class MoreLessColumn(tables.TemplateColumn):
78 """
79 Useful for displaying long fields.
80 A preview is shown initially with a "Show more" link
81 which is replaced with a "Show less" link when expanded.
82 """
84 template_name = "columns/more-less.html"
86 def __init__(self, preview, fulltext, *args, **kwargs):
87 self.preview = preview
88 self.fulltext = fulltext
89 super().__init__(template_name=self.template_name, *args, **kwargs)
91 def render(self, record, **kwargs):
92 self.extra_context["preview"] = self.preview(record)
93 self.extra_context["fulltext"] = self.fulltext(record)
94 return super().render(record, **kwargs)