[Django]-How do I limit a text length and add dots to show continuation python django

8๐Ÿ‘

โœ…

You can make use of the |truncatechars template filter [Django-doc]:

{{ product_name|truncatechars:23 }}

While you thus store the product_name as full text, it is rendered for the first 23 characters, and then followed by an ellipsis (โ€ฆ).

You can also add a tooltip that shows the text in full, for example:

<p title="{{ product_name }}">{{ product_name|truncatechars:23 }}</p>

3๐Ÿ‘

You can override save() method

def save(self, *args, **kwargs):
    if len(self.product_name) > 20:
        self.product_name = self.product_name[:20] + '...'
    super().save(*args, **kwargs)
๐Ÿ‘คweAreStarsDust

1๐Ÿ‘

You can get the length of a string using len

You can cut a string up using slices [:]

You can add the ellipsis to a string if the length is longer than a certain threshold.

if len(product_name) > 15:
    product_name = product_name[:15] + "..."
๐Ÿ‘คAlgoRythm

Leave a comment