Multiplication in django template

I move on carts and want to multiply the quantity with the unit price as follows:

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

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

+8
python django django-templates
source share
4 answers

You need to use a custom template tag. Template filters take only one argument, while a custom template tag can take as many parameters as you need, perform multiplication, and return the value to the context.

You can check the documentation for the Django template tag , but a quick example:

 @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 name so:

 {% 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 do not want this result to be a property of the cart item? It may seem that you need this information as part of your shopping cart when placing an order.

+14
source share

You can use the widthratio built-in filter for multiplication and division.

To calculate A * B: {% widthratio A 1 B %}

To calculate A / B: {% widthratio AB 1 %}

source: link

Note: for irrational numbers, the result is rounded to an integer.

+17
source share

Or you can set the property in 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 
+7
source share

You can do this in a filter template.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

From the documentation:

Here is an example of a filter definition:

 def cut(value, arg): """Removes all values of arg from the given string""" return value.replace(arg, '') 

And here is an example of using this filter:

 {{ somevariable|cut:"0" }} 
0
source share

All Articles