2👍
✅
You should use a DecimalField
for currency values not an integer field (otherwise you can’t have a budget such as 150.40)
class Category(models.Model):
name = models.CharField(max_length=128)
budget = models.DecimalField(default=0.0, decimal_places=2, max_digits=5)
class Meta:
verbose_number_plural = 'Categories'
def __unicode__(self):
return unicode(self.name) # always return unicode from __unicode__
# This method will be used in the admin display
def budget_display(self):
# Normally, you would return this:
# return '${0:1.2f}'.format(self.budget)
# but a decimal field will display itself correctly
# so we can just do this:
return '${0}'.format(self.budget)
budget_display.short_description = 'Budget'
You can use any callable in the list_display
, so instead of displaying the field, we call the function to return the correct format that we want.
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'budget_display')
Can you please explain what do you mean by ${0: 1.2f}
This is the new format string syntax:
>>> i = 123.45678
>>> '{0}'.format(i)
'123.45678'
>>> '{0:1.2f}'.format(i)
'123.46'
This {}
is a placeholder for whatever you will pass to format. I put a 0
in there to denote that I want the first argument to go there:
>>> '{0} {1}'.format('a', 'b')
'a b'
>>> '{1} {0}'.format('a', 'b')
'b a'
The :
in {0:
is the start of the format specification, which allows control of how things are displayed:
>>> '{0:.2f}'.format(123.456)
'123.46'
>>> '{0:.3f}'.format(123.456)
'123.456'
>>> '{0:.3f}'.format(.456)
'0.456'
Source:stackexchange.com