12

I am looping through cart-items, and want to multiply quantity with unit-price like this:

{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}

Is it possible to do something like that? any other way to do it !! Thanks

iblazevic
  • 2,713
  • 2
  • 23
  • 38
vijay shanker
  • 2,517
  • 1
  • 24
  • 37
  • possible duplicate of [multiplication in django template without using manually created template tag](http://stackoverflow.com/questions/18350630/multiplication-in-django-template-without-using-manually-created-template-tag) – Fernando Freitas Alves Oct 25 '13 at 13:56
  • That's a clever use of a filter. I didn't think to use `cart_item.quantity` as the `value` and `cart_item.unit_price` as the `arg` – Brandon Taylor Oct 25 '13 at 14:37

4 Answers4

40

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.

AppHandwerker
  • 1,758
  • 12
  • 22
‌‌R‌‌‌.
  • 2,818
  • 26
  • 37
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.

Paolo
  • 20,112
  • 21
  • 72
  • 113
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
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
Martin
  • 141
  • 1
  • 2
-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" }}
iblazevic
  • 2,713
  • 2
  • 23
  • 38