What is `@stringfilter` in Django?

117 views Asked by At

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?

1

There are 1 answers

0
Super Kai - Kazuya Ito On

@stringfilter can convert the 1st argument(parameter) to str type.

The doc says below about @stringfilter:

If you’re writing a template filter that only expects a string as the first argument, you should use the decorator stringfilter. This will convert an object to its string value before being passed to your function

For example, pass the 1st argument 3 and the 2nd argument 7 to test filter as shown below:

# "templates/index.html"

{% load custom_tags %}

{{ 3|test:7 }} # Here

Then, only the 1st parameter num1 is str type as shown below:

# "templatetags/custom_tags.py"

@register.filter(name="test")
@stringfilter # Here
def test_filter(num1, num2):
    print(type(num1), type(num2)) # <class 'str'> <class 'int'>
    return

Be careful, if the order of @stringfilter and @register.filter is opposite, the 1st parameter is not converted to str type as shown below:

# "templatetags/custom_tags.py"

@stringfilter # Here
@register.filter(name="test") # Here
def test_filter(num1, num2):
    print(type(num1), type(num2)) # <class 'int'> <class 'int'>
    return

In addition, you can use @stringfilter with @register.simple_tag, @register.tag or @register.inclusion_tag as shown below. *If the order of @stringfilter and @register.simple_tag, @register.tag or @register.inclusion_tag is opposite, the 1st parameter is not converted to str type:

# "templatetags/custom_tags.py"

@register.simple_tag(name="test")
@stringfilter
def test_tag(num1, num2):
    print(type(num1), type(num2)) # <class 'str'> <class 'int'>
    return
# "templatetags/custom_tags.py"

@register.tag(name="test")
@stringfilter
def test_tag(parser, token):
    print(type(parser), type(token)) # <class 'str'> <class 'django.template.base.Token'>
    return PersonNode()

class PersonNode(Node):
    def render(self, context):
        return ""
# "templatetags/custom_tags.py"

@register.inclusion_tag(name='test', filename='result.html')
@stringfilter
def test_tag(num1, num2):
    print(type(num1), type(num2)) # <class 'str'> <class 'int'>
    return