Django - 向管理员显示不同的模板

9-b*_*its 7 django django-permissions

在Django中,为具有"admin"权限的用户实现具有额外功能的模板的最佳方式是什么.

我不确定是否应该为管理员创建一组完全不同的视图,或者将其集成到我现有的视图和模板中,例如"if user is a admin".

在Django中有标准的方法吗?

小智 7

只有当您处于活动状态且员工不是管理员时,才会显示这些内容:

{% if request.user.is_active and request.user.is_staff %}
    {% include "foo/bar.html" %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

如果您只想显示,而且仅限管理员,您必须这样做:

{% if request.user.is_superuser %}
    ADD your admin stuff there.
{% endif %}
Run Code Online (Sandbox Code Playgroud)

这里有关于这些领域的差异.


Mar*_*mro 3

如果您在模板上下文中有可用的用户,您可以执行以下操作:

{% if user.is_active and user.is_staff %}
    Only the admin will see this code. For example include some admin template here:
   {% include "foo/bar.html" %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

RequestContext如果您使用并且您的TEMPLATE_CONTEXT_PROCESSORS设置包含,则用户将在您的模板中可用django.contrib.auth.context_processors.auth,这是默认值。请参阅模板中的身份验证数据作为参考。