[Fixed]-Use a django built in filter in code (outside of a template)

3👍

Depends on the filter. In some cases you can import the module that contains the filter and access a helper function within the module, but in other cases you won’t be so lucky. See the filter source for details.

40👍

Generally, yes. For example, if your filter is in django.template.defaultfilters you can run:

from django.template.defaultfilters import slugify
slugify('what is that smell')

If you peruse the code though you might notice that many of these filters import code from django.utils.text and django.utils.html so you can also skip the middle-person indirection and import the function directly from those packages as they are now also publicly documented.

from django.utils.text import slugify
slugify('progress arcs in fits and starts')
👤A Lee

4👍

Instead of using this in the template:

{{text | linebreaks}}

I used this to implement the linebreak filter:

from django.template.defaultfilters import linebreaks
text = "some text \n next line"
text = linebreaks(text)

gives:

<p>some text <br /> new line</p>
👤DevB2F

Leave a comment