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.
{% %} 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.
A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With