Fetching a Blog in Django

I am creating a blogging application in Django, and when I display all the blogs, I want to display a small excerpt of the blog with each post. Can someone tell me how can I do this?

One way to do this is to make an extra field and keep a fixed number of words for each blog entry, say 20 words. But then it will store redundant information in the database. Is there a better way to do this?

+8
python django blogs
source share
3 answers

I suggest you use the truncatewords template template.

Template example:

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

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

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

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

(displays the first 10 characters).

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

+14
source share

In Django 1.4 and later, there is a truncatechars filter that truncates a string to a specific length and ends it with ... , It actually truncates it to a specific length minus 3, and the last 3 characters become ...

+2
source share

A little bit connected.

I just answered this question: The Django template filter strip_tags adds space that can help others when creating excerpts containing HTML tags and short content in <p> tags.

Helps convert this.

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

to that..

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

instead of this..

 'This is a paragraph.This is another paragraph.' 
+1
source share

All Articles