Django:如果用户不是超级用户,则在模板中隐藏按钮 [英] Django: Hide button in template, if user is not super-user

查看:370
本文介绍了Django:如果用户不是超级用户,则在模板中隐藏按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取模板/视图以识别登录用户是否是超级用户?



如果用户不是超级用户,则我的表单上的某些按钮(模板中)需要完全隐藏



您将如何去做?

解决方案

查看 is_superuser User 对象上:

  {%,如果有要求。 user.is_superuser%} 
...
< button> ...< / button>
...
{%else%}
...
{%endif%}






编辑: @ mustafa-0x评论后



以上假设您的 TEMPLATE_CONTEXT_PROCESSORS 设置其中包含 django.core.context_processors.request 不是默认值



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

已包含 django.contrib.auth.context_processors.auth (并且明显不包括 request 上下文处理器),这意味着在大多数情况下,您已经可以访问 {{用户}} ,而无需通过视图将其添加到上下文中,或启用 request 上下文处理器通过 {{request.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?

解决方案

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

这篇关于Django:如果用户不是超级用户,则在模板中隐藏按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆