"read more" in django posts

I am creating a blog on django / webfaction. Currently, my homepage displays all content from all posts. I would like to configure it to show only a few lines from each post, and each post ends with a β€œread more” link. How to achieve this? I am new to django and python. Please help me.

Code in home.html:

{% block content %} {% for post in object_list %} <h2>{{ post.title }} </h2> <div class = "post_meta"> on {{ post.created}} </div> <div class = "post_body"> {{ post.body|safe|linebreaks}} </div> {% endfor %} {% endblock %} 

Thanks in advance.

+4
source share
2 answers

You can use the built-in template filter truncate doc

  <div class = "post_body"> {{ post.body|safe|truncatewords:"50"|linebreaks }} <a href="{{ url_for_full_content }}">read more</a> </div> 
+12
source

You can see the implementation of the SplitField field SplitField in django-model-utils extention:

 from django.db import models from model_utils.fields import SplitField class Article(models.Model): title = models.CharField(max_length=100) body = SplitField() >>> a = Article.objects.all()[0] >>> a.body.content u'some text\n\n<!-- split -->\n\nmore text' >>> a.body.excerpt u'some text\n' >>> unicode(a.body) u'some text\n\n<!-- split -->\n\nmore text' 

He correctly does exactly what you need. Read more in the doc .

+2
source

Source: https://habr.com/ru/post/1438343/


All Articles