I sometimes see @stringfilter with @register.filter.
So, I created test filter with @stringfilter as shown below:
# "templatetags/custom_tags.py"
from django.template import Library
from django.template.defaultfilters import stringfilter
register = Library()
@register.filter(name="test")
@stringfilter # Here
def test_filter(num1, num2):
return
But, it accepted int type values without error as shown below:
# "templates/index.html"
{% load custom_tags %}
{{ 3|test:7 }} # Here
I thought that @stringfilter only accepts str type values giving error for the other types.
So, what is @stringfilter in Django?
@stringfilter can convert the 1st argument(parameter) to
strtype.The doc says below about
@stringfilter:For example, pass the 1st argument
3and the 2nd argument7totestfilter as shown below:Then, only the 1st parameter
num1isstrtype as shown below:Be careful, if the order of
@stringfilterand @register.filter is opposite, the 1st parameter is not converted tostrtype as shown below:In addition, you can use
@stringfilterwith @register.simple_tag, @register.tag or @register.inclusion_tag as shown below. *If the order of@stringfilterand@register.simple_tag,@register.tagor@register.inclusion_tagis opposite, the 1st parameter is not converted tostrtype: