AttributeError:' ReturnDict'对象没有属性' pk'

时间:2016-07-19 02:24:04

标签: python django authentication django-rest-framework

我正在尝试为用户登录和注销设计api。但是我遇到了AttributeError错误:' ReturnDict'对象没有属性' pk'。可能是什么造成了这个错误?

enter image description here

详细追溯

File "/home/tushant/Projects/nepMart/account/api/views.py", line 61, in post
    login(request, serializer.data)
  File "/home/tushant/.virtualenvs/NepMart/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 102, in login
    if _get_user_session_key(request) != user.pk or (
AttributeError: 'ReturnDict' object has no attribute 'pk'

Serializers.py

class UserLoginSerializer(ModelSerializer):
    token = CharField(allow_blank=True, read_only=True)
    username = CharField(required=False, allow_blank=True)
    # email = EmailField(label='Email Address',required=False, allow_blank=True)
    remember = BooleanField(default=True, help_text = ("If checked you will stay logged in for 3 weeks"))
    class Meta:
        model = User
        fields = [
            'username',
            # 'email',
            'password',
            'remember',
            'token',

        ]
        extra_kwargs = {"password":
                            {"write_only": True}
                            }

views.py

class UserLoginAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UserLoginSerializer

def post(self, request, *args, **kwargs):
    data = request.data
    serializer = UserLoginSerializer(data=data)
    if serializer.is_valid(raise_exception=True):
        # new_data = serializer.data
        print('request.data', request.data)
        print('serializer.data',serializer.data)
        login(request, serializer.data)
        if data.get('remember'):
            request.session.set_expiry(60 * 60 * 24 * 7 * 3)
        else:
            request.session.set_expiry(0)
        return Response({
            'detail': ('Logged in successfully'),
            # TODO: maybe more user info in the request would have sense
            'username': serializer.data.username
        })
    return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

ifincase usercreation is needed

class UserCreateSerializer(ModelSerializer):
    email = EmailField(label='Email Address')
    email2 = EmailField(label='Confirm Email Address')
    class Meta:
        model = User
        fields = [
            'username',
            'id',
            'password',
            'email',
            'email2',
        ]
        extra_kwargs = {"password":
                            {"write_only": True}
                        }

    def create(self, validated_data):
        print('validated_data',validated_data)
        username = validated_data['username']
        email = validated_data['email']
        email2 = validated_data['email2']
        password = validated_data['password']
        user_obj = User(
                username=username,
                email=email
            )
        user_obj.set_password(password)
        user_obj.save()
        return validated_data

2 个答案:

答案 0 :(得分:0)

登录前,您应该使用authenticate方法。像这样:

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)
        # Redirect to a success page.
    else:
        # Return a 'disabled account' error message
        ...
else:
    # Return an 'invalid login' error message.
    ...

答案 1 :(得分:0)

在序列化程序类Meta中的UserLoginSerializer类内部: fields还应包含属性id。 我尝试了这个,这为我解决了这个问题。

class UserLoginSerializer(ModelSerializer):
    token = CharField(allow_blank=True, read_only=True)
    username = CharField(required=False, allow_blank=True)
    # email = EmailField(label='Email Address',required=False, allow_blank=True)
    remember = BooleanField(default=True, help_text = ("If checked you will stay logged in for 3 weeks"))
    class Meta:
        model = User
        fields = [
            'username',
            'id',  // required
            # 'email',
            'password',
            'remember',
            'token',

        ]

请留言并寻求帮助,如果这不能解决您的问题。