F
F
fovka2020-06-03 00:15:21
Django
fovka, 2020-06-03 00:15:21

How to properly create your own context_processors in Django?

I'm sorry, but I didn't understand the documentation. I want to make the context available in all templates, but not rewrite all its variables in each view.
1. I create context_processors.py at the same level as settings.py:

from django.core.context_processors import request
def site(request):
    return {'key':'arg',...}

2. In settings.py I write:
TEMPLATES = [
    {  ...
        'OPTIONS': {
            'context_processors': [
                ...
                'context_processors.site'
            ],
        },
    },
]

3. I hope now to get access to {{ key }} from any template. But hopes are broken by an error:
No module named 'context_processors'

Where am I stupid?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2020-06-03
@fovka

Wangyu that the path is wrong. Try something like this 'project_name.context_processors.site'

M
Maxim Alyukov, 2020-06-03
@mvxmvl

You don't need to create your own context processor. In this situation, templatetags will do.

  1. In the application directory, create a templatetags directory .
  2. In the templatetags directory, create the __init__.py file and the tag name (let it be some_tags.py) .
  3. In some_tags.py paste the code below.
  4. In <> characters your code

# Файл some_tags.py 
from django import template
from monitoring.models import <Your model> 

register = template.Library()

@register.simple_tag()
def get_<some>():
    return <Your model>.objects.all()

# В файлах .html
{% load some_tags %} # Подгружаем теги
{% get_<some> as objects %} # Используем функцию, которую прописали в файле some_tags.py
{% for obj in objects %}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question