Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

388
Views
How to subtract two fields in django templates?

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 }}
about 4 years ago · Santiago Trujillo Report

0

There is an alternative way as I tried to explain here:

Variable subtraction in django templates

I'm sure this method can be applied to your question too.

I'm pretty sure it's still better to go with a custom template helper anyway.. It's also not wrong to add the calculated value to your view / model imo.

Hope this helps..

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!