85👍
You can use the built-in widthratio
template tag.
- a*b use
{% widthratio a 1 b %}
- a/b use
{% widthratio a b 1 %}
Note: the results are rounded to an integer before returning.
@see https://docs.djangoproject.com/en/dev/ref/templates/builtins/
32👍
There are 2 approaches:
- Computing the values inside the view and pass them to the template (recommended in my opinion)
- Using template filters
In the manner of the add
filter, you could always create your own multiply
filter, creating your own custom filter:
from django import template
register = template.Library()
@register.filter
def multiply(value, arg):
return value * arg
Then in your template, something like that should work.
{{ quantity | multiply:price }}
This is not tested, and I never did this as – again – I find neater to compute datas inside the views and render only with the templates.
- [Django]-What's the reason why Django has SmallIntegerField?
- [Django]-Django Cache cache.set Not storing data
- [Django]-Django/Python Beginner: Error when executing python manage.py syncdb – psycopg2 not found
10👍
Another approach that I have used seems cleaner to me. If you are going through a queryset, it doesn’t make sense to compute the values in your view. Instead, add the calculation as a function in your model!
Let’s say your model looks like this:
Class LineItem:
product = models.ForeignKey(Product)
quantity = models.IntegerField()
price = models.DecimalField(decimal_places=2)
Simply add the following to the model:
def line_total(self):
return self.quantity * self.price
Now you can simply treat line_total as if it were a field in the record:
{{ line_item.line_total }}
This allows the line_total
value to be used anywhere, either in templates or views, and ensures that it is always consistent, without taking up space in the database.
- [Django]-Django error: needs to have a value for field "…" before this many-to-many relationship can be used
- [Django]-Identify the changed fields in django post_save signal
- [Django]-Django: Query using contains each value in a list
5👍
I know it’s been so long since this question came out but, now there’s a library called django-mathfilters which made mathematical operations easier in Django templates. you can easily write
<li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
for multiplication.
check it out https://pypi.org/project/django-mathfilters/
- [Django]-How to query directly the table created by Django for a ManyToMany relation?
- [Django]-How do I display the value of a Django form field in a template?
- [Django]-Internationalisation Django (on OSX)
1👍
Multiplication with variable in Django.
1st: install & then register "mathfilters" at INSTALLED_APPS in setting.py
2nd: Add {% load mathfilters %} in html Page
3rd: Multiply with variable like{{response.notSatisfied|mul:100}}
- [Django]-Passing arguments to model methods in Django templates
- [Django]-Case insensitive urls for Django?
- [Django]-Django Rest Framework – Get related model field in serializer