Django does not provide a built-in template tag/filter to do subtraction. Also, there is no built-in filter for converting a positive integer to negative. You would have to write a template tag for that.
Solution 1- Use a custom template filter:
@register.filter
def subtract(value, arg):
return value - arg
Then in your template, you can do something like:
{{ pagecontrol.start_page|subtract:pagecontrol.news_per_page }}
Solution 2- Use django-mathfilters library
You can use Django-mathfilters library to get a subtract filter.
First, load mathfilters at the top of your template. Then use sub filter in your template like below:
{% load mathfilters %}
{{ pagecontrol.start_page|sub:pagecontrol.news_per_page }}
Why your code is not working?
Django Source code of add built-in filter:
@register.filter(is_safe=False)
def add(value, arg):
"""Adds the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
try:
return value + arg
except Exception:
return ''
When you do {{ pagecontrol.start_page|add:"-pagecontrol.news_per_page" }} in your template, '-pagecontrol.news_per_page' string is passed as arg to the above add built-in filter and not its actual value, so exception is raised because of adding integer and string values. '' is returned as the final value by add filter so nothing is displayed.
NOTE:
In case of complex variables name, you can use with template tag. It will cache a complex variable under a simpler name.
Below is a sample example of using with with add filter. This will just add the values.
{% with my_variable=pagecontrol.news_per_page %}
This will store the value of pagecontrol.news_per_page in the variable my_variable. Then in your template, you can use this variable:
{{ pagecontrol.start_page|add:my_variable }}
This will add the 2 variables.
{% with my_variable=pagecontrol.news_per_page %}
{{ pagecontrol.start_page|add:my_variable }}
{% endwith %}