Bases: DecimalField
Enter and display percentages out of 100 but store them out of 1
in db as decimals
Because this is based on models.DecimalField
, decimal_places
applies to what is
stored in the db (/1), not what is shown or typed in (/100). With that said, add two
(2) to whatever is desired in the form for proper validation.
Source code in django_rubble\fields\db_fields.py
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 | class SimplePercentageField(models.DecimalField):
"""Enter and display percentages out of 100 but store them out of 1
in db as decimals
Because this is based on `models.DecimalField`, `decimal_places` applies to what is
stored in the db (/1), not what is shown or typed in (/100). With that said, add two
(2) to whatever is desired in the form for proper validation.
"""
description = _(
"percentage (max {max_digits} digits; {decimal_places} decimal places"
)
log_name = "models.PercentageField"
def __init__(
self,
verbose_name=None,
name=None,
max_digits=None,
decimal_places=None,
**kwargs,
):
if decimal_places is not None:
self.humanize_decimal_places = int(decimal_places) - 2
else:
self.humanize_decimal_places = None
kwargs.update(
{
"max_digits": max_digits,
"decimal_places": decimal_places,
}
)
super().__init__(verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {"form_class": SimplePercentageFormField}
if self.decimal_places is not None:
kwargs.update(decimal_places=self.decimal_places - 2)
defaults.update(kwargs)
return super().formfield(**defaults)
|