Is there a way to add a thousand separator in Django admin for DecimalField?
This is my models.py
, inhabitants field is what I am concerned about:
class City(models.Model):
name = models.CharField(max_length=100)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
inhabitants = models.DecimalField(
max_digits=19,
decimal_places=2,
blank=True,
null=True,
)
class Meta:
verbose_name = "City"
verbose_name_plural = "Cities"
def __str__(self):
return self.name
This is how it looks in my the most basic custom view(no thousand separator, only a decimal separator, that I have described in models.py
):
I then went into settings.py
and added this - USE_THOUSAND_SEPARATOR = True
.
Now in the same custom view I see a thousand separators (commas).
However, in Django admin, nothing changes, thousand separator is not present, even with USE_THOUSAND_SEPARATOR = True
in settings.py
.
Am I missing a feature or its not intended to be displayed with thousand separators in Django admin for some reason?
Thank you!
Edit: when I think about it deeper … it probably should not be possible to add the thousand separators. It’s kind of raw data that we are editing in the Admin… that is why it is not allowed to add the physical commas in between the numbers. In the UI - where I am not modifying the data, its possible. Unless use JS and add commas that way(which is probably what Django would do also). Something similar to this:
q = id_inhabitants
<input type=​"number" name=​"inhabitants" value=​"100000000.00" step=​"0.01" id=​"id_inhabitants">​
q.value
'100000000.08'
parseFloat(q.value).toLocaleString();
'100,000,000.08'
document.getElementById('id_inhabitants').type="text"
'text'
q.value = parseFloat(q.value).toLocaleString();
'100,000,000.08'
and then we get the commas:
But then if we try to save this value, it of course gives us an error:
The specified value “100,000,000.10” cannot be parsed, or is out of range.
Django does not like that it’s not a number field anymore. So then we also must change the DecimalField to CharField. Then make sure only numbers without commas go to the db… quite a lot of work.