如何使用自定义用户模型从Django注销?

时间:2019-04-08 20:32:04

标签: django django-authentication

我制作了一个应用程序,并扩展了AbstractUser,以向我的User模型添加一些字段。完成之后...一切都按预期工作(登录,创建用户,重置密码...),但是当我尝试使用默认值注销时 django.contrib.auth.LogoutViewinclude('django.contrib.auth.urls') 它只会忽略注销。当我返回到受限页面时,我可以输入并看到内容,而我的用户实际上已经登录!!

我创建了这样的自定义退出视图

def custom_logout(request):
    print('Loggin out {}'.format(request.user))
    auth.logout(request)
    print(request.user)
    return HttpResponseRedirect('/restrictedpage')

在受限制的页面上,我有一张打印纸显示给用户 print("User logged: {}".format(request.user))

当我单击注销时,控制台中将显示以下内容:

"GET /restrictedpage  HTTP/1.1" 200 19820
User logged: ceterre
 ----- This is where i click logout ------
Loggin out AnonymousUser
AnonymousUser
"GET /accounts/logout/ HTTP/1.1" 302 0  ----- this redirects me to /restrictedpage
User logged: ceterre
"GET /restrictedpage HTTP/1.1" 200 19820

这字面意思是:

 - i know ceterre is logged
 - logging out ceterre
 - user logged: AnonymousUser
 - redirect to restricted page (where i should have no access since im supposedly logged out)
 - user logged: ceterre (without any login or anything...)

它可能与缓存有关,或者我不知道。

3 个答案:

答案 0 :(得分:0)

登录和注销是Django(以及AbstractUser)的一部分,因此您无需扩展这部分代码。您必须做的一件事是在settings.py文件中添加以下两行代码:

enum B

答案 1 :(得分:0)

from django.contrib.auth import logout

def custom_logout(request):
    print('Loggin out {}'.format(request.user))
    logout(request)
    print(request.user)
    return HttpResponseRedirect('/restrictedpage')

这对我有用,也应该对您有用。

答案 2 :(得分:0)

这是适用于Django 3+的解决方案。

django.contrib.admin模块替换my_admin

INSTALLED_APPS = [
        ...
        'my_admin.apps.AdminConfig',
        # 'django.contrib.admin',
        ...
]

AdminConfig(my_admin / apps.py):

from django.contrib.admin.apps import AdminConfig as ContribAdminConfig

class AdminConfig(ContribAdminConfig):
    default_site = 'my_admin.admin_site.AdminSite'

AdminSite(my_admin / admin_site.py):

from django.contrib.admin import AdminSite as ContribAdminSite
from django.views.decorators.cache import never_cache

class AdminSite(ContribAdminSite):
    @never_cache
    def logout(self, request, extra_context=None):
        """
        Define your custom logout functionality here.
        Checkout the super logout method to get a baseline implementation.
        
        Log out the user for the given HttpRequest.
        This should *not* assume the user is already logged in.
        """

        # Your logout code here.

        return super().logout(request, extra_context)