Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use a django built in filter in code (outside of a template)

I am formatting a string in python and I would like to use one of django's built in filters that is typically used in a template. Is there an easy way to use it in lines of code?

like image 498
MattoTodd Avatar asked Apr 07 '11 17:04

MattoTodd


People also ask

What does the built in Django template filter safe do?

This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.


3 Answers

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')
like image 87
A Lee Avatar answered Oct 09 '22 17:10

A Lee


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.

like image 29
Ignacio Vazquez-Abrams Avatar answered Oct 09 '22 16:10

Ignacio Vazquez-Abrams


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>
like image 3
DevB2F Avatar answered Oct 09 '22 16:10

DevB2F