How to add, multiply number variables in a Django template?

Use django-mathfilters. The addition filter doesn't coerce numbers to integer so you can add floats:

{% load mathfilters %}
{{ num1 | addition:num2 }}

It's possible to use django built-in widthratio template tag and add filter:

  • add 5 to forloop.counter {{forloop.counter|add:5}}
  • subtract 5 from forloop.counter {{forloop.counter|add:"-5"}}
  • devide forloop.counter by 5 {% widthratio forloop.counter 5 1 %}
  • multiply forloop.counter by 5 {% widthratio forloop.counter 1 5 %}

I make the next in my template file carts.html

{% extends 'base.html'%} {% block contenido %}
<h1>Checkout</h1>
<p>Subtotal + IVA: ${{ orden.sub_total }}</p>
<p>Envio:$ {{ orden.costo_envio }}</p>
<p>Total a pagar:$ {{ orden.sub_total|add:orden.costo_envio }}</p>
{% endblock %}

where my view based function is:

def carrito_checkout(request):
    if 'cart_id' in request.session:
        orden_object, created = Orden.objects.get_or_new(request)
        if orden_object is None:
            return redirect('carrito:home')
        print(orden_object)
        context = {
            "orden": orden_object
        }

    return render(request, 'carrito_checkout.html', context=context)

For me this aproach works fine

enter image description here


There is the filter add from the documentation.

I'm pretty sure there are no built-in way to use the other mathematical operations over numbers in Django templates. You can always make your own however. It is not always a good idea to do so.

You want to keep your logic inside the views and keep the rendering inside the templates.

In your case, you should store your counter in a JavaScript variable, and use it in your snippet.