Multiply by -1 in a Django pattern

I would always like to use the positive value of my variable in a Django template. The sign of the variable is a text value:

{% if qty > 0 %} Please, sell {{ qty }} products. {% elif qty < 0 %} Please, buy {{ -qty }} products. {% endif %} 

Of course, {{ -qty }} doesn't work.

Is there a workaround without passing a second variable containing an absolute value? Something like a template filter that converts a value to an unsigned integer.

Thanks!

+6
source share
4 answers

You can use some string filters:

 {% if qty > 0 %} Please, sell {{ qty }} products. {% elif qty < 0 %} Please, buy {{ qty|slice:"1:" }} products. {% endif %} 

or

  Please, sell {{ qty|stringformat:"+d"|slice:"1:" }} products. 

But you should probably do this in your view or write your own filter.

+11
source

To do this, you must use a special filter.

Here are two different ways to do this:

1) You can define a negate filter:

 # negate_filter.py from django import template register = template.Library() @register.filter def negate(value): return -value 

Then, in your template, add the code {% load negate_filter %} to the top of the page, and then replace {{ -qty }} with {{ qty|negate }} .

2) You can also replace the whole thing with one buy_sell filter, if you want:

 # buy_sell_filter.py from django import template register = template.Library() @register.filter def buy_sell(value): if value > 0 : return 'sell %s' % value else : return 'buy %s' % -value 

Then your template should be

 {% if qty %} Please, sell {{ qty|buy_sell }} products.{% endif %} 

You can even include the entire line in the filter and just have the complete template {{qty | buy_sell}}.

Both options are reasonable, depending on the rest of your template. For example, if you have many lines that use the purchase for the negative and sell for the positive, do the second.

+4
source

Like everything else in Python, there is a library for this: django-mathfilters .

Then you can simply use the abs filter as follows:

 Please, sell {{ qty|abs }} products. 
+2
source

Ideally, you should perform a check in your view, separate the logic from the display (for example, what happens if qty = 0?) If you insist on doing the math in the template, you can do something like this hack .

Another option is to write a custom filter (see this example ).

+1
source

All Articles