11

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?

Sachin
  • 3,672
  • 9
  • 55
  • 96
  • Depending on if you want the excerpt to be editable or not determines the correct answer. Could do it simply with a def excerpt(self) and return the body chopped to a certain string length and then sanitize the html if any. – William Stearns Oct 25 '11 at 19:21

3 Answers3

21

I suggest you use the truncatewords template filter.

Template example:

<ul>
{% for blogpost in blogposts %}
    <li><b>{{blogpost.title}}</b>: {{blogpost.content|truncatewords:10}}</li>
{% endfor %}
</ul>

If the blog content is stored as HTML, use truncatewords_html to ensure that open tags are closed after the truncation point (or combine with striptags to remove html tags).

If you want to truncate on characters (not words), you can use slice:

{{blogpost.content|slice:":10"}}

(outputs first 10 characters).

If content is stored as HTML, combine with striptags to avoid open tags problems: {{blogpost.content|striptags|slice:":10"}}

MichielB
  • 4,181
  • 1
  • 30
  • 39
codeape
  • 97,830
  • 24
  • 159
  • 188
  • 1
    This will truncate the words to a specific length... However is there anything if I want to truncate to a specific number of characters because words can be longer in length and I don't want my box to be becoming too big – Sachin Oct 25 '11 at 19:33
  • If you do decide to add a summary field in your blog model, you can fallback to the truncatewords if the summary is blank (using if and else tags in template). But generally the truncate template tag/filter is the popular method for doing this. – j_syk Oct 25 '11 at 19:35
  • @Sachin: Updated answer w/ truncate to character count. – codeape Oct 25 '11 at 19:47
  • `striptags` saved my day. Thanks for this advice! – n2o Jun 20 '15 at 15:51
2

In Django 1.4 and later, there's a truncatechars filter that will truncate a string to a specific length and terminate it with .... It actually truncates it to the specific length minus 3, and the last 3 characters become the ....

Holly
  • 1,059
  • 1
  • 13
  • 16
1

Somewhat related..

I just provided an answer to this question: Django strip_tags template filter add space that may help others when making excerpts that contain HTML tags and short content in <p> tags.

Helps convert this..

"<p>This is a paragraph.</p><p>This is another paragraph.</p>"

to this..

'This is a paragraph. This is another paragraph.'

instead of this..

'This is a paragraph.This is another paragraph.'
Community
  • 1
  • 1
robnardo
  • 921
  • 11
  • 27