I've got a blog app in Django. I want to show the latest 3 blog posts on another page but can only show all of the blog posts ordered by date.
How can I show the latest 3 posts?
Do I filter this in the views or on the template tags?
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True, max_length=255, null=True)
pub_date = models.DateTimeField()
excerpt = models.TextField(null=True)
text = models.TextField()
header_image = models.FileField(upload_to='blog/%Y/%m/%d', null=True, blank=True)
post_color = models.CharField(max_length=20, null=True)
tags = models.CharField(max_length=80, blank=True)
published = models.BooleanField(default=True)
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('blog.views.post', args=[self.slug])
from django.shortcuts import render, get_object_or_404
from blog.models import Post
def about(request):
# get the blog posts that are published
posts = Post.objects.filter(published=True).order_by('-pub_date')
# now return the rendered template
return render(request, 'blog/about.html', {'post': posts})
{% for post in post %}
<section class="post">
<h3><a class="post-title"
href="{{post.get_absolute_url}}">
{{ post.title }}
</a></h3>
<span class="post-meta">
{{ post.pub_date | date:"d F Y" }}
</span>
<p class="post-excerpt">
{{ post.excerpt }}
</p>
</section>
{% endfor %}
Try this,
posts = Post.objects.filter(published=True).order_by('-pub_date')[0:3]
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