我有一个问题与authenticate()
方法。它总是返回无。我检查了我所有的参数,他们不是空的。在模型中,我有USERNAME_FIELD = 'username'
,在设置中,我有AUTH_USER_MODEL = 'account.User'
。我真的不明白为什么它不工作。
models.py
class UserManager(BaseUserManager):
def _create(self, username, password):
if not username:
raise ValueError('Username cant be empty')
user = self.model(username=username)
user.set_password(raw_password=password)
user.save()
return user
def create_user(self, username, password):
return self._create(username=username, password=password)
class User(AbstractBaseUser):
id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='id')
email = models.EmailField()
username = models.CharField(max_length=25, unique=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
education = models.CharField(max_length=100, blank=True)
date_of_birth = models.DateField(blank=True, null=True)
name = models.CharField(max_length=25, blank=True)
last_name = models.CharField(max_length=25, blank=True)
objects = UserManager()
USERNAME_FIELD = 'username'
views.py
class UserLoginView(ObtainAuthToken):
serializer_class = UserLoginSerializer
serializers.py
class UserLoginSerializer(serializers.Serializer):
username = serializers.CharField(required=True)
password = serializers.CharField(required=True)
def validate_username(self, username):
if not User.objects.filter(username=username).exists():
raise serializers.ValidationError('User wasn\'t found')
print(User.objects.get(username=username).password)
return username
def validate(self, data):
# authentications
request = self.context.get('request')
username = data.get('username') # test_name
password = data.get('password') # newpassword11
if username and password:
user = authenticate(username=username, password=password, request=request)
print(user)
if not user:
raise serializers.ValidationError('Invalid password')
else:
raise serializers.ValidationError('You have to type you\'re mail and password')
data['user'] = user
return data
3条答案
按热度按时间nfs0ujit1#
我通过将模型更改为以下内容修复了它:
在将post请求发送到url路由到
UserLoginView
视图后,post主体处的username
和password
在响应处获得类似于以下内容的Json:当使用
AbstractBaseUser
而不是AbstractUser
时,请注意实现Django用户模型的所有要求。提示:不要忘记正确设置
DRF Authentication
。wecizke32#
问题出在
users
字段,称为is_active
。Django只允许在用户处于活动状态时使用login
。另外,感谢所有人,他们尽力帮助我们:)
wko9yo5t3#
对于任何可能与此错误斗争的人来说,我也面临着同样的问题,并发现我缺少的是在设置文件中声明auth设置。