[Answered ]-How to display latest 5 posts by pub date?

2๐Ÿ‘

โœ…

You can pass the latest 5 posts (ordered by creation_date) to the template using order_by:

def blog(request):
    return render_to_response('home/blog.html', {
        'posts': Post.objects.order_by('-creation_date')[:5]
    })

The - preceding creation_date indicates that the dates returned will be in descending order, ie the most recent date first.

To add the functionality to display the next 5 posts, I would return the 10 most recent Posts to the template using the method I have suggested, and then manipulate these using another method (perhaps basic JavaScript),

๐Ÿ‘คgtlambert

0๐Ÿ‘

def blog(request):
    return render(request, 'home/blog.html', {
        'posts': Post.objects.order_by('-creation_date')[:5]
    })

render instead of render_to_response, which takes care of context instance for you.

๐Ÿ‘คdoniyor

Leave a comment