1 回答
TA贡献1906条经验 获得超3个赞
好的,多亏了 Shafikur Rahman 的建议,我才能让它发挥作用。在我尝试调试它pdb并在里面设置跟踪LoginUserSerializer但没有发生任何事情之后,我意识到在我的视图中我不是指向我编写的序列化程序,而是指向AuthTokenSerializer. 即使在那之后它仍然不起作用,因为我对 djangologin()和 DRF 的validate()工作原理缺乏了解。以下固定代码供参考:
看法:
class LoginUserView(LoginView):
serializer_class = LoginUserSerializer
permission_classes = [AllowAny]
def post(self, request, *args, **kwargs):
serializer = LoginUserSerializer(data=request.data) # changed to desired serializer
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
login(request, user)
return super(LoginUserView, self).post(request)
和序列化器:
class LoginUserSerializer(serializers.ModelSerializer):
username = serializers.CharField() # added missing fields for serializer
password = serializers.CharField()
class Meta:
model = UserModel
fields = ('username', 'password')
def validate(self, data):
user = authenticate(**data)
if user:
if user.is_active:
data['user'] = user # added user model to OrderedDict that serializer is validating
return data # and in sunny day scenario, return this dict, as everything is fine
raise exceptions.AuthenticationFailed('Account is not activated')
raise exceptions.AuthenticationFailed()
另外为了authenticate()不能激活用户,我不得不添加
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.AllowAllUsersModelBackend'
]
在项目设置中。
添加回答
举报