Hi everybody.

My question is. I made an html template that I will extend in every other html pages. And this template have some variables. So my question is how to assign a function to this base template.
Let me be more clear and give you an example:

base.html

...
...
    {% if auth_form.has_errors %}
        ---- do something -----

    {% if true_flag %}
        ----- do something ----


    and so on...
....
....

some_page.html

{% extends 'base.html' %}

    ----------do something -------

So my question is how to create a function in views.py (or I don't know may be I have to change urls.py) in such way that in some_page.html I don't need to specify what is auth_form or true_flag.....

Dani AI

Generated

As described, the goal is to make a handful of variables available to every template that extends the base. As suggested, the usual, clean solution is a custom context processor — a small callable that returns a dictionary of names that every template will receive.

A minimal example (place under an app, e.g. myapp/context_processors.py):

from django.contrib.auth.forms import AuthenticationForm

def global_vars(request):
    # create whatever objects you need per-request (pass request to forms if your Django version expects it)
    auth_form = AuthenticationForm(request)
    true_flag = request.user.is_authenticated and request.user.is_staff
    return {'auth_form': auth_form, 'true_flag': true_flag}

Then register it in your settings so the template engine calls it for each render. For modern Django put the dotted path inside TEMPLATES[...]['OPTIONS']['context_processors']:

# settings.py (Django 1.8+)
'OPTIONS': {
    'context_processors': [
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'myapp.context_processors.global_vars',
    ],
},

Troubleshooting and tips: context processors run frequently, so keep them cheap and avoid heavy DB work at module import time. If a value really depends on that specific view (URL params, form validation state, etc.), supply it from the view (get_context_data for CBVs or the view’s context dict) instead of the global processor. Don’t forget to restart the dev server after changing settings. Also check you return a plain dict and that your templates are rendered with the standard Django template engine (or RequestContext in very old versions). Context processors are ideal for site-wide bits (navigation, site name, small forms), while view-specific flags belong in the view.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.