我使用Django-rest-framework做一个小项目。 在下面提示最佳实践样式代码,这将使其更简单。
class LoginSerializer(serializers.Serializer):
phone = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
phone = data.get("phone", "")
password = data.get("password", "")
# need simplify the structure below
if phone and password:
user = authenticate(phone=phone, password=password)
if user:
if user.is_active:
data['user'] = user
else:
raise exceptions.ValidationError('User is deactivated.')
else:
raise exceptions.ValidationError(
'Unable to login with given credentials.')
else:
raise exceptions.ValidationError(
'Must provide username and password both.')
return data