简体   繁体   English

如何在Django的管理网站中添加“注销”功能

[英]How to add 'logout' function to a Admin site in Django

In my Django project, I created a separate admin.py and in that file, I extend the AdminSite class as follows: 在我的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

But then I discovered that in that admin site, there is no link on the top left to the logout. 但是后来我发现,在该管理站点中,左上角没有退出链接。 How do I add that to the admin site? 如何将其添加到管理站点?

If you are extending AdminSite you should already have a logout function, 如果您要扩展AdminSite,则应该已经具有注销功能,

https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L349 : 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)

if you look at the admin site's base.html it's looking for url with the namespace admin:logout 如果您查看管理站点的base.html,它将使用名称空间admin:logout查找url。

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

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

Are you overwriting the default admin urls.py? 您是否要覆盖默认的admin urls.py? You can check the Django docs here for details on setting namespace. 您可以在此处查看Django文档以获取有关设置名称空间的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM