Creating Custom Context Processors

Article by Wayne Fagan. Published on 4 Mar, 2020.

A context processor is a method with a `HttpRequest` object which returns a dictionary (context), this object once registered is available throughout all templates within the project.

As an example `request` has it's own context processor. When you call `{{ request.user.first_name }}` in a template you are using the context processor which is registered in `TEMPLATES` in `settings.py` as `"django.template.context_processors.request"`.

Creating your own custom context processor is relatively simple.

Say you have a `news` app in your project, you would create a file entitled `context_processors.py` within the directory of this app. Then within this file you would add:

from . import models


def articles(request):
    return {
        'article_selection': models.Article.objects.published()[:10],
    }

This context processor will return 10 published articles when the key `article_selection` is used in the template.

Next you will need to add the new context processor to `settings.py`, by locating the constant variable `TEMPLATES` and adding `news.context_processors.articles` to the `context_processors` list.

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'OPTIONS': {
        'context_processors': [
            ...

            'news.context_processors.articles',
            
            ...
        ],
        'loaders': [
            'django.template.loaders.app_directories.Loader',
        ],
        'debug': DEBUG
    }
}]

Now in your template you can now call `article_selection` as a context processor. For example you can now iterate through the `article_selection` queryset like so:

{% for article in article_selection %}
  {{ article.title }}
{% endfor %}