gpt4 book ai didi

python - 类型错误 : get_session_auth_hash() missing 1 required positional argument: 'self'

转载 作者:行者123 更新时间:2023-12-01 04:26:48 24 4
gpt4 key购买 nike

我正在学习 Django,试图实现一个自定义用户模型,但每次我尝试用它登录/admin 时,我都会得到两个以 结尾的长回溯列表

TypeError: get_session_auth_hash() missing 1 required positional argument: 'self'

回溯中的单个文件或调用都不是我的文件之一

以防万一,这是我的模型和后端文件

模型.py

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser

class UserManager(BaseUserManager):
"""
Custom user manager
"""
def create_user(self, username, password):
if not username or not password:
raise ValueError("We need username and password here...")
user = self.model(username=username)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, password):
if not username or not password:
raise ValueError("We need username and password here...")
user = self.create_user(username=username,password=password)
user.set_password(password)
user.is_admin = True
user.is_staff = True
user.save()
return user

class User(AbstractBaseUser):
"""
Custom user class
"""
username = models.CharField(max_length=64, unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True, auto_now=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'username'

def __str__(self):
return self.username

后端.py

from django.contrib.auth.models import check_password
from accounts.models import User

class AuthenticationBackend(object):
"""
Backend for authentication
"""
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None

def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return User
return None
except User.DoesNotExist:
return None

最佳答案

AuthenticationBackend.get_user中,您有:

        if user.is_active:
return User

它实际上返回 User class 而不是您的 user 实例。调用此方法的代码稍后会尝试根据您返回的内容调用 get_session_auth_hash(),因此会出现错误。

你想要:

        if user.is_active:
return user

关于python - 类型错误 : get_session_auth_hash() missing 1 required positional argument: 'self' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com