How to use django filters in python code

Okay, so django is pretty nice. It's a great web framework with a very straightforward templating engine, and I'm sad to be leaving it for Rails-land for the time being. One of the nice things about django is the set of included template tags and variable filters. You can define blocks of code that can then be overwritten by templates that inherit the given template, and you can very easily format your data in view-specific ways. The variable filters in particular come in handy. Very often.

In fact, there are times when it would be nice to be able to use those filters outside of django template code. In the true spirit of DRY, I don't want to recreate django's date filter, file size formatter, slugify tool, etc.

So how do you use django filters in plain old python? Turns out it's pretty easy:

def process_data():

from django.template import defaultfilters
page_title = "How to use django filters in python code"
page_slug = defaultfilters.slugify(page_title)
# page_slug == "how-to-use-django-filters-in-python-code"

file_size = 123456789
file_size_display = defaultfilters.filesizeformat(file_size)
# file_size_display == "117.7 MB"

And there you have it. Good stuff. If you don't want to keep typing "defaultfilters" you can alias it, of course.

from
django.template import defaultfilters as filters
page_slug = filters.slugify(page_title)

You can call any filter from the built-in list this way. The first argument is the value upon which to perform the filter, the second argument is (optionally) the string argument used as additional information for some formats. So

{{
value|date:"D d M Y" }}

becomes

defaultfilters.date(value, "D d M Y")


Pretty straightforward stuff. Obviously this only works for the default filters. If you've added any more filters, you should know already where they're located and how to call them.

Comments

Unknown said…
Thank you - this is exactly what I was looking for.

I like your blog, I read this blog please update more content on python, further check it once at python online training
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man learn Python Online Course
Unknown said…
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man learn Python Online Course

Popular Posts