Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"read more" in django posts

I am creating a blog on django/webfaction. Currently my home page displays all the contents from all the posts. I would like to tweak it to show only few lines from each post and each post ending with a "read more" link. How to achieve this? I am new to django and python. Kindly 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.

like image 722
Robby Avatar asked Oct 08 '12 04:10

Robby


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What is escape in Django?

Definition and Usage The escape filter escapes HTML characters from the value. Note: Escaping HTML characters is a default setting in Django, so we have to turn off autoescape in the example to be able to see the difference.

What are template tags in Django?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. In the next chapters you will learn about the most common template tags.


2 Answers

You can use 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>
like image 128
iMom0 Avatar answered Oct 12 '22 06:10

iMom0


You can see the implementation of the field model 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'

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

like image 32
defuz Avatar answered Oct 12 '22 04:10

defuz