[Django]-How to list latest posts in Django?

2👍

The reason this doesn’t work is because the published_at is apparently NULL and is thus never filled in. With the .filter(published_at__lte=timezone.now()), it checks that the published_at is less than or equal to the current timestamp. If it is NULL, it thus is excluded. That means that you will either need to fill in the published_at some way, or filter (and order) with a different field, like created_at. You can thus work with:

from django.db.models.functions import Now
from django.shortcuts import get_object_or_404, render

from .models import Category, Post


def post_list(request):
    posts = Post.objects.filter(created_at__lte=Now()).order_by('-created_at')
    latest_posts = posts[:5]
    context = {'posts': posts, 'latest_posts': latest_posts}
    return render(request, 'list_posts.html', context)


def post_detail(request, pk, post):
    latest_posts = Post.objects.filter(created_at__lte=Now()).order_by(
        '-created_at'
    )[:5]
    post = get_object_or_404(Post, pk=pk)
    context = {'post': post, 'latest_posts': latest_posts}
    return render(request, 'post_detail.html', context)

Note: You can work with Now [Django-doc] to work with the database timestamp instead. This can be useful if you want to specify the queryset in a class-based view, since each time the queryset is evaluated, it will then take the (updated) timestamp.

Leave a comment