template.defaultfilters.stringfilter()

django.template.defaultfilters.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:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def lower(value):
    return value.lower()

This way, you’ll be able to pass, say, an integer to this filter, and it won’t cause an AttributeError (because integers don’t have lower() methods).

doc_Django
2016-10-09 18:39:46
Comments
Leave a Comment

Please login to continue.