A
A
Albadur2019-04-11 19:06:26
Django
Albadur, 2019-04-11 19:06:26

How to pass variable to base template?

There are many pages on the site, they all inherit from one base.
It is necessary to pass the variable to the base template so that these variables are not written for each page.
According to the Django documentation, this can be done using the RequestContext.
This code from the documentation works great

from django.http import HttpResponse
from django.template import RequestContext, Template

def ip_address_processor(request):
    return {'ip_address': request.META['REMOTE_ADDR']}

def client_ip_view(request):
    template = Template('{{ title }}: {{ ip_address }}')
    context = RequestContext(request, {
        'title': 'Your IP Address',
    })
    return HttpResponse(template.render(context))

Problem starts when trying to include html file
def home(request):
    template = get_template('home/home.html')
    context = RequestContext(request, {
        'title': 'Your IP Address',
    })
    return HttpResponse(template.render(context))

An error is thrown: TypeError: context must be a dict rather than RequestContext.
Please help. Thank you very much in advance.
Answer: RequestContext is not needed at all. You need to register a context processor, specify it in settings.
def custom_proc(request):
    "A context processor that provides 'app', 'user' and 'ip_address'."
    param = request.session.get('Param')
    data = {"param":param}
    return data

In Processors Templates inserted name_of_folder.name_of_file.custom_proc

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-04-11
@Albadur

Most likely you need a context processor .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question