User variable inaccessible in template tag

Hi. I’m fairly inexperienced in Web Dev and Django.

I need to check if user is_staff or not, in my HTML page, specifically in a custom template tag I’ve written. My base.html is as follows:

<body>
    <header>
        This is the Header.
        <h1>Webiste name & logo</h1>
        <hr>
        <nav>
            <h2>This is the navigation bar</h2>
            {% show_traits %}
        </nav>
        <hr>
    </header>
    {% block content %}{% endblock %}
    <hr>
    <footer>
        Here starts the footer.
        <a href="{% url 'login' %}">Sign In</a>
        <a href="{% url 'register' %}">Sign Up</a>
    </footer>
</body>

The first line loads tags from my_tags.py file, which has the following:

from django import template
from ..models import Trait

register = template.Library()


@register.inclusion_tag('navigation.html')
def show_traits():
    traits = Trait.objects.all()
    return {'traits': traits}

The navigation.html file is as follows:

This is the user: {{ user.username }}
<ul>
    {% for trait in traits %}
        <li>
            {% if user.is_staff %}
                <a href="{% url 'form-detail' trait.id %}">{{ trait }}</a>
            {% else %}
                <a href="#">{{ trait }}</a>
            {% endif %}
        </li>
    {% endfor %}
</ul>

My app/urls.py file is fine I believe:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.show_homepage, name='home-page'),
    path('form/<int:id>/', views.show_form_detail, name='form-detail'),
]

But when I run my dev server, the base.html file doesn’t seem to show the {{user}} variable:

image

The page source shows that the user wasn’t validated as staff either:

 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <header>
        This is the Header.
        <h1>Webiste name & logo</h1>
        <hr>
        <nav>
            <h2>This is the navigation bar</h2>
            This is the user: 
<ul>
    
        <li>
            
                <a href="#">Depression</a>
            
        </li>
    
        <li>
            
                <a href="#">Extraversion</a>
            
        </li>
    
</ul>
        </nav>
        <hr>
    </header>
    
    <hr>
    <footer>
        Here starts the footer.
        <a href="/user/login">Sign In</a>
        <a href="/user/register/">Sign Up</a>
    </footer>
</body>
</html>

Even though I’m logged in as Admin. Could you please help me figure out what I’m doing wrong. My settings file is as follows:

INSTALLED_APPS = [
    'formsapp',
    'Dummy',
    'crispy_forms',
    'users',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mental_health_app.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mental_health_app.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home-page'

My root directory structure is as follows:
I have 3 apps: Dummy, formsapp & users in addition to the main project app named “mental_health_app”.

By default, Inclusion tags don’t pass the context into the function. You either need to pass the user in as a parameter or define the function with the takes_context parameter.

Ken

2 Likes