Thomas' Tech Tips

Print only first N characters of string in Django template

10 May 2023 - Thomas Damgaard

I recently started using Django for a hobby-project I am working on.

I often find myself wanting to only print the first N characters of a text field in a template. For example, if you don’t want to clutter a table or similar.

The way to show only the first N characters of a string is by using |slice:N, where N is the number of characters to show.

Example use:

{{ deal.next_action | slice:50}}

However, often when you want to truncate a text like this, you typically also want to add ... at the end if the string is truncated.

Luckily, Django has a built in function for this: truncatechars.

Example use:

{{ deal.next_action | truncatechars:50}}
Filed under: django, howto, python, tips

Back to article list