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

时间:2012-02-25 20:29:22

标签: django django-permissions

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

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

在Django中有标准的方法吗?

3 个答案:

答案 0 :(得分:7)

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

{% if request.user.is_active and request.user.is_staff %}
    {% include "foo/bar.html" %}
{% endif %}

如果您只想展示管理员,那么您必须这样做:

{% if request.user.is_superuser %}
    ADD your admin stuff there.
{% endif %}

有关这些字段的差异here

答案 1 :(得分:2)

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

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

如果您使用RequestContext并且TEMPLATE_CONTEXT_PROCESSORS设置包含django.contrib.auth.context_processors.auth,则您的模板中将提供用户,这是默认设置。请参阅authentication data in templates作为参考。

答案 2 :(得分:2)

我主张在视图层之外保留尽可能多的逻辑(一般来说关于MVC设计模式)。那么为什么不使用装饰器根据用户的特权将用户引导到不同的视图呢?在您的urls.py中,为管理员定义模式:

url(r'^admin/$', 'user.views.admin_index'),
#do so for your other admin views, maybe more elegantly than this quick example

然后定义一个装饰器,如果用户不是管理员,则将用户踢出去

def redirect_if_not_admin(fn):
def wrapper(request):
    if request.user.is_staff():
        return fn(request)
    #or user.is_superuser(), etc
    else:
        return HttpResponseRedirect('/Permission_Denied/')
return wrapper

在您的管理员视图中

@redirect_if_not_admin
def index(request):
##do your thing 

它的代码多于其他两个答案,这些都没有错。在视图中保持混乱只是个人偏好。