21👍
You need to use a custom template tag. Template filters only accept a single argument, while a custom template tag can accept as many parameters as you need, do your multiplication and return the value to the context.
You’ll want to check out the Django template tag documentation, but a quick example is:
from django import template
register = template.Library()
@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
# you would need to do any localization of the result here
return qty * unit_price
Which you can call like this:
{% load your_custom_template_tags %}
{% for cart_item in cart.cartitem_set.all %}
{% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}
Are you sure you don’t want to make this result a property of the cart item? It would seem like you’d need this information as part of your cart when you do your checkout.
41👍
You can use widthratio
builtin filter for multiplication and division.
To compute A*B: {% widthratio A 1 B %}
To compute A/B: {% widthratio A B 1 %}
source: link
Notice: For irrational numbers, the result will round to integer.
- Advanced Django Template Logic
- Django reverse to contains/icontains
- Improving Performance of Django ForeignKey Fields in Admin
- Drf-spectacular is using the wrong AutoSchema to generate Swagger
14👍
Or you can set the property on the model:
class CartItem(models.Model):
cart = models.ForeignKey(Cart)
item = models.ForeignKey(Supplier)
quantity = models.IntegerField(default=0)
@property
def total_cost(self):
return self.quantity * self.item.retail_price
def __unicode__(self):
return self.item.product_name
- Installing PIL to use with Django on Mac OS X
- Django – Custom Admin Actions Logging
- Django 1.5 admin inline extra
-1👍
You can do it in template with filters.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters
From documentation:
Here’s an example filter definition:
def cut(value, arg):
"""Removes all values of arg from the given string"""
return value.replace(arg, '')
And here’s an example of how that filter would be used:
{{ somevariable|cut:"0" }}
- Docker compose could not open directory permisson denied
- How does django's View class work
- How can I generate a url to a particular item in the Django Admin Site from a view?