Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract two fields in django templates?

Tags:

python

django

Before marking as duplicate to numerous other questions on SO, read. I have three fields, Credit Available, Credit Limit and Credit Balance. I'm getting the values for Credit Limit and Credit Balance from my database. To display Credit Available, I want to do Credit Limit-Credit Balance. I tried doing this from other answers on stackoverflow, but they did not work

<tr>
    <td style="text-align:center">{{ credit.credit_limit|add:"-{{credit.credit_balance}}" }}</td>
    <td align="center">{{ credit.credit_limit}}</td>
    <td align="center">{{ credit.credit_balance }}</td>
</tr>

Can I do this without writing new template tags or using the mathfilter module?

like image 829
DeA Avatar asked Oct 21 '25 12:10

DeA


1 Answers

The correct syntax for adding the limit to the balance is

{{ credit.credit_limit|add:credit.credit_balance }}

as per https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#add. Unfortunately, putting a minus sign in front of a variable won't work to make it negative.

You could use a custom template filter, which would be fairly straightforward. It might look like this:

@register.filter(name='subtract')
def subtract(value, arg):
    return value - arg

Then in your template (after loading it) it would be:

{{ credit.credit_limit|subtract:credit.credit_balance }}
like image 159
nimasmi Avatar answered Oct 23 '25 01:10

nimasmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!