Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do you get your template/view to recognize whether or not a logged in user is a super user or not?

There are certain buttons on my forms (in the template) that I want completely hidden if the user is not a super-user

How would you go about doing that?

like image 356
JohnnyCash Avatar asked Apr 08 '12 19:04

JohnnyCash


People also ask

How do I know if my Django user is superuser?

in admin panel superuser box is checked.

What does {% %} mean in Django?

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.

When {% extends %} is used for inheriting a template?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

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 }}

like image 137
Timmy O'Mahony Avatar answered Oct 14 '22 21:10

Timmy O'Mahony


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.

like image 21
shuckc Avatar answered Oct 14 '22 21:10

shuckc