How to pass data to any template without passing it through the views in Django | global model(database) data for every template.

You can pass data to any template of your project , following below five steps –

Create context_processors.py file in app folder

As , shown in above picture , you have to create context_processors.py file in your app folder of django project.

Import Model & return it in form of dictionary via a function.

In , context_processors.py file you have to return the model or table of database in the form of dictionary , so that you can access this model from any templates in django.

You can import & return model like –

from app1_book.models import Number_store

def apple(request):
    number=Number_store.objects.all()
    return {'number':number}

Here , ‘app1_book’ is a app name & ‘Number_store’ is a model.

Mention this function path in settings.py file

In settings.py file of django , in TEMPLATES, you have to add the path of function which you have created in context_processors.py file like –

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',
                'app1_book.context_processors.apple',
            ],
        },
    },
]

Use this database or model data in any templates

Now , you can use this data of model , in any templates file in your project like –

As ‘number’ is passed as dictionary in context_processors.py file , so using it like below in template-

{% for i in number %}
        <h3 >{{i.topic}}</h3>
        <h4 >{{i.num}}</h4>
{% endfor %}