【问题标题】:How do I redirect users who try to access admin area in Django?如何重定向尝试访问 Django 管理区域的用户?
【发布时间】:2011-09-12 11:30:30
【问题描述】:

我注意到 Django 的管理区域存在一个有趣的问题。如果我撤销我的员工权限并尝试直接访问/admin,我通常希望在查询字符串中使用/admin/ 重定向到我的登录页面作为未来的重定向。但是,我得到了一个返回 HTTP 代码 200 的正确页面,它实际上使用我的 admin/login.html 模板来呈现请求的页面而不是重定向。看来问题出在 @staff_member_required 装饰器上,管理员视图显然使用了该装饰器。

问题是:这是故意的吗?如果没有,我怎样才能在没有太多猴子补丁的情况下改变这种行为?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    这是故意这样做的,因为许多人在他们的网站中实施重定向,这可能会阻止对管理面板的访问。因为管理面板是它自己的应用程序,所以它会重定向到自己。

    # Put this code somewhere it will be imported REALLY early
    
    from django.contrib.admin.views import decorators
    
    def staff_member_required(view_func):
        """
        Decorator for views that checks that the user is logged in and is a staff
        member, displaying the login page if necessary.
        """
        def _checklogin(request, *args, **kwargs):
            if request.user.is_active and request.user.is_staff:
                # The user is valid. Continue to the admin page.
                return view_func(request, *args, **kwargs)
            else:
                return HTTPResponseRedirect('/my/login/page/')
        return wraps(view_func)(_checklogin)
    
    decorators.staff_member_required = staff_member_required #replaces the function in-place
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多