-2

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>

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

[![home page][1]][1]

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'

2 Answers2

0
  • To get the user's username in the template, you should use {{ user.get_username }}.
  • I think your template for staff validation is already correct. Have you checked that this user really is_staff? You can check from your localhost URL with /admin logging in with your superuser.
gunsodo
  • 175
  • 1
  • 10
0

I found out that the user context variable, though accessible from base.html or other template files, isn't accessible by default in a custom template tag file. I had to provide user as an explicit context variable to my template tag function. I changed my template tag file as follows:

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

and my "base.html" as follows:

<h2>This is the navigation bar</h2>
{% show_traits user %}

And then it worked.