我正在使用django rest framework djoser身份验证。所以我想要的是当用户登录时,它将返回他们的用户令牌,promptms,status,first_name和last_name。
djoser:http://djoser.readthedocs.io/en/latest/introduction.html
现在我能够显示令牌,提示符和状态,但是对于first_name和last_name,我在尝试执行此操作时出错。
串行
class TokenCreateSerializer(serializers.Serializer):
password = serializers.CharField(
required=False, style={'input_type': 'password'}
)
default_error_messages = {
'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
}
def __init__(self, *args, **kwargs):
super(TokenCreateSerializer, self).__init__(*args, **kwargs)
self.user = None
self.fields[User.USERNAME_FIELD] = serializers.CharField(
required=False
)
def validate(self, attrs):
self.user = authenticate(
username=attrs.get(User.USERNAME_FIELD),
password=attrs.get('password')
)
self._validate_user_exists(self.user)
self._validate_user_is_active(self.user)
return attrs
def _validate_user_exists(self, user):
if not user:
self.fail('invalid_credentials')
def _validate_user_is_active(self, user):
if not user.is_active:
self.fail('inactive_account')
customviews.py
class CustomTokenCreateView(cutils.ActionViewMixin, generics.GenericAPIView):
"""
Use this endpoint to obtain user authentication token.
"""
serializer_class = TokenCreateSerializer
permission_classes = [permissions.AllowAny]
def _action(self, serializer):
token = utils.login_user(self.request, serializer.user)
token_serializer_class = settings.SERIALIZERS.token
content = {
'Token': token_serializer_class(token).data["auth_token"],
'promptmsg': 'You have successfully login',
'status': '200',
'first_name': self.request.user.first_name,
'last_name': self.request.user.last_name
}
return Response(
data=content,
status=status.HTTP_200_OK,
)
此代码会出错:
AttributeError at /logintest/
'AnonymousUser' object has no attribute 'first_name'
有没有办法解决这个问题?
答案 0 :(得分:3)
身份验证请求在其标头中不包含身份验证令牌,这就是request.user
返回AnonymousUser对象的原因。
要解决此错误,您需要将request.user
替换为serializer.user
,如下所示:
content = {
'Token': token_serializer_class(token).data["auth_token"],
'promptmsg': 'You have successfully login',
'status': '200',
'first_name': serializer.user.first_name,
'last_name': serializer.user.last_name
}