Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only show the latest 3 posts in Django?

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?

models.py

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])

views.py

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})

about.html

{% 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 %}
like image 271
David Ingledow Avatar asked Dec 14 '22 22:12

David Ingledow


1 Answers

Try this,

posts = Post.objects.filter(published=True).order_by('-pub_date')[0:3]
like image 126
dhana Avatar answered Dec 17 '22 11:12

dhana