I have to subtract two values in django templates. How can I do this ?
{{ obj.loan_amount }} - {{ obj.service_charge }}
There are 2 ways to do this.
1) The more preferred way (based on separation of business logic and template logic), is to calculate what you are trying to do in the views.py, and then pass the value through the context. For example:
class FooView(View):
def get(self, request, *args, **kwargs):
obj = Foo.objects.get(pk=1)
obj_difference = obj.loan_amount - obj.service_charge
return render(request, 'index.html', {'obj': obj,
'obj_difference': obj_difference})
this would allow you to use {{ obj_difference }}
outright in your template.
2) The second way to do this, which is less desirable, is to use template tags.
@register.simple_tag(takes_context=True)
def subtractify(context, obj):
newval = obj.loan_amount - obj.service_charge
return newval
this would allow you to use {% subtractify obj %}
in your template.
Note: If you use method #2, don't forget to use {% load [tagname] %}
in the top of your HTML file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With