【问题标题】:How to add 'logout' function to a Admin site in Django如何在 Django 中向管理站点添加“注销”功能
【发布时间】:2015-04-21 21:28:15
【问题描述】:

在我的 Django 项目中,我创建了一个单独的 admin.py,并在该文件中,我扩展了 AdminSite 类,如下所示:

class UserAdminSite(AdminSite):
    site_header = "Admin Site"
    site_title = "Manage User and Groups"
    login_form = AuthenticationForm

def has_permission(self, request):
    return request.user.is_active and request.user.is_admin_user

但后来我发现在那个管理站点中,左上角没有指向注销的链接。如何将其添加到管理站点?

【问题讨论】:

    标签: python django


    【解决方案1】:

    如果你正在扩展 AdminSite,你应该已经有一个注销功能,

    https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L349:

    @never_cache
    def logout(self, request, extra_context=None):
        """
        Logs out the user for the given HttpRequest.
        This should *not* assume the user is already logged in.
        """
        from django.contrib.auth.views import logout
        defaults = {
            'current_app': self.name,
            'extra_context': dict(self.each_context(request), **(extra_context or {})),
        }
        if self.logout_template is not None:
            defaults['template_name'] = self.logout_template
        return logout(request, **defaults)
    

    如果您查看管理站点的 base.html,它正在寻找名称空间为 admin:logout 的 url

    https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/base.html#L46:

    <a href="{% url 'admin:logout' %}">{% trans 'Log out' %}</a>
    

    您是否覆盖了默认的管理员 urls.py?您可以查看 Django 文档here 了解设置命名空间的详细信息。

    【讨论】:

    • 我没有覆盖默认的管理员 urls.py。当我通过输入地址手动访问管理站点的注销页面时,它工作正常。只是管理站点的左上角没有“退出”按钮。
    猜你喜欢
    • 2010-12-30
    • 2011-01-17
    • 2019-05-06
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多