I am building a blog application in Django and when I display all the blogs I want to display a small blog excerpt with each entry. Can anybody tell me how can I do that?
One way to do that would be to make an extra field and store a fixed number of words for
each blog entry, let’s say 20 words. But then that would be storing redundant information
in the database. Is there a better way to do that?
I suggest you use the truncatewords template filter.
Template example:
If the blog content is stored as HTML, use
truncatewords_htmlto ensure that open tags are closed after the truncation point (or combine withstriptagsto remove html tags).If you want to truncate on characters (not words), you can use
slice:(outputs first 10 characters).
If content is stored as HTML, combine with
striptagsto avoid open tags problems:{{blogpost.content|striptags|slice:":10"}}