[Django]-Django: Hide button in template, if user is not super-user

122👍

Check out is_superuser on the User object:

{% if request.user.is_superuser %}
    ...
    <button>...</button>
    ...
{% else %}
...
{% endif %}

EDIT: after @mustafa-0x comments

The above assumes that you have django.core.context_processors.request included in your TEMPLATE_CONTEXT_PROCESSORS setting which isn’t the default.

The default setting for TEMPLATE_CONTEXT_PROCESSORS:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
#    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
)

already includes the django.contrib.auth.context_processors.auth (and notably doesn’t include the request context processor) meaning that in most cases you will already have access to {{ user }} without the need to add it to your context via the view, or enable the request context processor to access the user as above via {{ request.user }}

21👍

As discussed in the comments, you can use the User object that is available in templates automatically:

{% if user.is_superuser %}
<div class="alert alert-success" role="alert">
You are logged in as {{user.first_name}}, here are the
<a href="/admin/">admin pages</a> for changing content.
</div>
{% endif %}

You can also use user.is_staff which might be more appropriate.

👤shuckc

0👍

Actually when you try to check on the login html template weather the user is superuser or not you will not be able to do that because at that very instance it will be false you can check it in views.py file that user is super or not and then redirect it where ever you want.
you can do some thing like this as you can see in start function

Leave a comment