【问题标题】:Django - Showing different templates to adminsDjango - 向管理员显示不同的模板
【发布时间】:2012-02-25 20:29:21
【问题描述】:

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

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

在 Django 中有标准的方法吗?

【问题讨论】:

    标签: django django-permissions


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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 作为参考。

      【讨论】:

        【解决方案3】:

        我主张在视图层之外保留尽可能多的逻辑(一般来说是关于 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 
        

        它比其他两个答案的代码更多,这并没有错。在视图中保持混乱只是个人喜好。

        【讨论】:

          猜你喜欢
          • 2014-09-08
          • 2011-03-12
          • 2019-09-22
          • 2015-11-19
          • 2016-09-10
          • 2014-12-01
          • 1970-01-01
          • 2021-09-14
          • 2016-06-20
          相关资源
          最近更新 更多