Sobes.tech
Middle
221

What is a context processor in Django?

Answer from AI

sobes.tech AI

A context processor in Django is a callable (callback function) that takes an HTTP request as an argument and returns a dictionary of variables. This dictionary is added to the context of every template processed by this request.

They are used to add common data to all templates without needing to explicitly pass this data in each view.

Common examples include:

  • Adding data of the authenticated user.
  • Adding site settings (e.g., name, domain).
  • Adding information about the current request (e.g., path).

Context processors are configured in Django settings:

# settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Custom processors can be added here
                #'my_app.context_processors.my_custom_processor',
            ],
        },
    },
]

Example of a custom context processor:

# my_app/context_processors.py

def my_custom_processor(request):
    # Function takes request
    return {
        'site_name': 'My Awesome Site',  # Returns a dictionary
        'current_year': 2023,
    }

After adding it in settings.py, the variables site_name and current_year will be available in any template:

<!-- my_template.html -->
<p>Welcome to {{ site_name }}!</p>
<p>&copy; {{ current_year }}</p>