Django create a custom model field for currencies
Here I my custom model field I created it
class CurrencyAmountField(models.DecimalField):
INTEGER_PLACES = 5
DECIMAL_PLACES = 5
DECIMAL_PLACES_FOR_USER = 2
MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES
MAX_VALUE = Decimal('99999.99999')
MIN_VALUE = Decimal('-99999.99999')
def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS,
decimal_places=DECIMAL_PLACES, **kwargs):
super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits,
decimal_places=decimal_places, **kwargs)
How can I show the numbers in a comma-separated mode in Django admin forms? Should I override some method here on this custom model field or there is another to do that?
Should be:
First:
MAX_VALUE = Decimal('99999.99999')
90.000 < 333.222.111 It gives you validation error if you write 333222111. In your question you use this number.
Second:
on image you have input
and textarea
. To get a textarea
you should change widget = TextInput in field.
class CurrencyAmountField(models.DecimalField):
widget = Textarea
You can do it also in form. You can do it also in modelAdmin. And you dont need your own Field class.
Third:
you can use MaxValueValidator, MinValueValidator instead of MAX_VALUE, after that - you don't need to create you own field class.
myAmount = DecimalField(max_digits=10, decimal_places=5, validators=[MaxValueValidator(Decimal('99999.99999')), MinValueValidator(Decimal('-99999.99999'))])
Four:
check your settings. more here: https://docs.djangoproject.com/en/4.1/ref/settings/#std-setting-USE_THOUSAND_SEPARATOR
USE_THOUSAND_SEPARATOR, USE_L10N, NUMBER_GROUPING, THOUSAND_SEPARATOR please write it in your question.
Five:
For this simply question you don't need to change any template.
While I have yet to manage to get the comma to display on input, I have managed to get the comma to display when viewing the saved model
This is what I have tried currently
# forms.py
class ValuesForm(forms.ModelForm):
class Meta:
model = Values
fields = ['value']
value = forms.DecimalField(localize=True)
#settings.py
USE_THOUSAND_SEPARATOR = True
#admin.py
class ValuesAdmin(admin.ModelAdmin):
form = ValuesForm
#models.py
class Values(models.Model):
value = models.DecimalField(max_digits=10, decimal_places=2
While documentation suggests it's possible to do it on input, it might require a custom widget, so I'll investigate that shortly.
As a working solution, I have replaced the comma with _
when inputting, manually.
e.g. 12_345_678
which gets displayed on save as 12,345,678