Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two variables in django template [duplicate]

I have to subtract two values in django templates. How can I do this ?

{{ obj.loan_amount }} - {{ obj.service_charge }}
like image 680
LaksHmiSekhar Avatar asked Mar 03 '15 10:03

LaksHmiSekhar


1 Answers

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.

like image 113
Hybrid Avatar answered Nov 03 '22 13:11

Hybrid