Django Context Processors Using a context processor to access your most recent blog entries in all templates


Assuming you have a model called Post defined in your file that contains blog posts, and has a date_published field.

Step 1: Write the context processor

Create (or add to) a file in your app directory called

from myapp.models import Post

def recent_blog_posts(request):
    return {'recent_posts':Post.objects.order_by('-date_published')[0:3],}  # Can change numbers for more/fewer posts

Step 2: Add the context processor to your settings file

Make sure that you add your new context processor to your file in the TEMPLATES variable:

        'OPTIONS': {
            'context_processors': [

(In Django versions before 1.9, this was set directly in using a TEMPLATE_CONTEXT_PROCESSORS variable.)

Step 3: Use the context processor in your templates

No need to pass recent blog entries through individual views anymore! Just use recent_blog_posts in any template.

E.g., in home.html you could create a sidebar with links to recent posts:

<div class="blog_post_sidebar">
    {% for post in recent_blog_posts %}
        <div class="post">
            <a href="{{post.get_absolute_url}}">{{post.title}}</a>
    {% endfor %}

Or in blog.html you could create a more detailed display of each post:

<div class="content">
    {% for post in recent_blog_posts %}
        <div class="post_detail">
            <p>Published on {{post.date_published}}</p>
            <p class="author">Written by: {{}}</p>
            <p><a href="{{post.get_absolute_url}}">Permalink</a></p>
            <p class="post_body">{{post.body}}</p>
    {% endfor %}