-
Notifications
You must be signed in to change notification settings - Fork 1
/
columns.py
91 lines (72 loc) · 2.48 KB
/
columns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from __future__ import annotations
from datetime import datetime
import django_tables2 as tables
from django.contrib.humanize.templatetags.humanize import NaturalTimeFormatter
from django.db.models import Choices, Model
from django.db.models.fields.files import ImageFieldFile
from django.utils.html import format_html
from django_countries import countries
from django_countries.fields import Country
from django_tables2.columns import BoundColumn
# TODO: probably not needed anymore
class ImageColumn(tables.Column):
def render(self, value: ImageFieldFile):
return format_html(
'<img src="{}" class="h-12" width={} height={} />',
value.url,
value.width,
value.height,
)
def value(self, record, value):
return value.url
class AvatarColumn(ImageColumn):
def render(self, value: ImageFieldFile):
return format_html(
"""
<div class="avatar">
<div class="w-12 rounded-xl">
<img src="{}" width={} height={} />
</div>
</div>
""",
value.url,
value.width,
value.height,
)
class CountryColumn(tables.Column):
attrs = {"td": {"data-flag": str(True).lower()}}
def render(self, value):
c_code = countries.by_name(value)
return format_html(
"<span title='{}'>{}</span>",
value,
Country(c_code).unicode_flag if c_code else value,
)
def value(self, value):
return value
class NaturalDatetimeColumn(tables.Column):
attrs = {"td": {"title": lambda bound_column, record: bound_column.accessor.resolve(record)}}
def value(self, value: datetime):
return value.replace(tzinfo=None)
def render(self, value: datetime):
return NaturalTimeFormatter.string_for(value)
class LabeledChoicesColumn(tables.Column):
def __init__(
self,
choices: type[Choices],
labels_replacements: dict[str, str] = None,
*args,
**kwargs,
):
self._choices = choices
self._labels_replacements = labels_replacements or dict()
super().__init__(*args, **kwargs)
def render(self, bound_column: BoundColumn, record: Model):
value = bound_column.accessor.resolve(record)
return format_html(
'<span title="{}">{}</span>',
label := self._choices(value).label,
self._labels_replacements.get(value) or label,
)
def value(self, record, value):
return value