In the template in django, we know that variables are presented using {{xxx}}, but how to deal with two variables when they occur for calculation?
#addition:{{value|add:value2}} #The result returned is the value of value+value2. Assuming that your value is 40 and value2 is 60, then the expression#Return result is 100
#Subtraction{{value|add -value2}} #The properties of addition are the same as the properties of addition, but the second parameter is turned into a negative number for operation. The returned result is value-value2#If value=4, value2=8, the returned result is -4
#multiplication{% widthratio value1 value2 value3%} #The above code means value1/value2*value3, widthratio requires three parameters, multiplication is just to equal the second parameter to 1#Example: value1=10 value2=1 value3=2 The returned result is 10/1*2=20
#division{% widthratio value1 value2 value3%} #The result returned is (value1/value2)*value3 Just equal value3 to 1 to perform division operation#Example: value1=100 value2=20 value3=1 The returned result is (100/20)*1=5
Data retains two decimal places
<td>{{ foo.product_amount |floatformat:5 }}</td> register = ()
Some more complex operations
Using the add filter, you can do even more crazy things:
- Calculate A^2: {% widthratio A 1 A %}
- Calculation (A+B)^2: {% widthratio A|add:B 1 A|add:B %}
- Calculation (A+B) * (C+D): {% widthratio A|add:B 1 C|add:D %}
Division and retain decimals
First define the method in the file
@ def div(value, div): ''' Convert the segments into elements, retaining two decimal places :param value: :param div: :return: ''' return round((value / div), 2)
Then in the template, you can use it as follows, of course, the premise is {% load templatehelper %}:
<td>{{ foo.product_amount |div:100 }}</td>
I have tried a stupid method, but it does not take effect. Even if it takes effect, it will ignore the value after the decimal point, so it is not recommended:
<td>{% widthratio foo.product_amount 100 1 as width %}{% blocktrans %}{{ width }}{% endblocktrans %}</td>#}
This is the end of this article about variable operations in Django templates. For more related content on variable operations in Django templates, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!