Hidden gems of Django: Truncator
Turns out Django offers great way to truncate text. Lets see how to use the built-in util Truncator.Published: Nov. 29, 2020 Sponsored Get the app
Recently I was working on a Django project and needed to truncate text. My first instinct was to google how to truncate text in Python. Which if course can be done, but the code isn't that elegant.
The most naive approach is to just slice the text and get like 40 first characters like this:
text[0:40]. But now you need the
... at the end, however only if the text was actually longer than 40 chars. And what if you don't want to split words in a middle?
To pick up the "story", after googling for a Python way for a bit, it occurred to me to try google how to truncate in Django and I found the gem called
This is a helper class to truncate text as the name implies. It handles this job very well and there is no need to look for anything else.
We start by importing it:
from django.utils.text import Truncator
You initialize the
Truncator with string you want to truncate.
test_text = "The part that took the longest was to display random banner on a page. This involves mainly getting random record (or entity if you will) from your database. I have found quite a few solutions but they were either too complicated or relied on some preconditions like you had to have a table with no deleted records + sequential ids and then you could use something like last id or count and select random number from that." truncator = Truncator(test_text)
I have used a paragraph from my recent Django post. All that is left to do is to tell the truncator the result we want. We can use either method
words to truncate based on number of words or
chars to truncate strictly on the character basis. The
words option is better, but if you have strict length limit, you need to opt for
And the output:
The part that took the longest was to display random banner on a page. This involves mainly getting random record…
And the output:
The part that took the longes…
Did you catch the "…" at the end? Those are not three separate dots but rather the ellipsis character. Neat touch.
That's the basic usage done.
Truncator actually has a few more tricks up its sleeves. You can pass
truncate parameter and specify, what string should denote truncation.
The part that took the longest was to display random___
If you are building a web app, chances are you want to truncate HTML text and
Truncator has you covered. You can pass
html=True and it will correctly handle HTML for you.
Now imagine handling all this yourself. This is why I like Django so much. And "batteries included" frameworks in general.