美文网首页
Django+Vue打造购物网站(七)

Django+Vue打造购物网站(七)

作者: 听你讲故事啊 | 来源:发表于2018-12-01 11:42 被阅读0次

    个人中心功能开发

    drf文档注释
    http://www.django-rest-framework.org/topics/documenting-your-api/

    动态设置serializer和permission获取用户信息

    获取详情只需要添加一个mixins.RetrieveModelMixin,就行了

    用户详情的序列化
    users/serializers.py

    class UserDetailSerializer(serializers.ModelSerializer):
        """
        用户详情
        """
        class Meta:
            model = User
            fields = ("name", "gender", "birthday", "email","mobile")
    

    views.py

    class UserViewset(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
        '''
        用户信息管理
        create:
            用户注册
        retrieve:
            个人信息
        update:
            修改个人信息
        '''
        queryset = User.objects.all()
        authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)
    
        def create(self, request, *args, **kwargs):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            user = self.perform_create(serializer)
    
            # 注册成功直接生成token,自动登陆
            re_dict = serializer.data
            payload = jwt_payload_handler(user)
            re_dict["token"] = jwt_encode_handler(payload)
            re_dict["name"] = user.name if user.name else user.username
    
            headers = self.get_success_headers(serializer.data)
    
            # 返回的不是serializer.data,而是我们自己写的re_dict
            return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
    
        # 这里需要动态权限配置
        # 1.用户注册的时候不应该有权限限制
        # 2.当想获取用户详情信息的时候,必须登录才行
        def get_permissions(self):
            if self.action == "retrieve":
                return [permissions.IsAuthenticated(), ]
            elif self.action == "create":
                return []
    
            return []
    
        # 这里需要动态选择用哪个序列化方式
        # 1.UserRegSerializer(用户注册),只返回username和mobile,会员中心页面需要显示更多字段,所以要创建一个UserDetailSerializer
        # 2.问题又来了,如果注册的使用userdetailSerializer,又会导致验证失败,所以需要动态的使用serializer
        def get_serializer_class(self):
            if self.action == "retrieve":
                return UserDetailSerializer
            elif self.action == "create":
                return UserRegSerializer
    
            return UserDetailSerializer
    
        # 虽然继承了Retrieve可以获取用户详情,但是并不知道用户的id,所有要重写get_object方法
        # 重写get_object方法,就知道是哪个用户了
        def get_object(self):
            return self.request.user
    
        def perform_create(self, serializer):
            return serializer.save()
    

    用户个人信息修改,只需要继承mixins.UpdateModelMixin就可以了

    用户收藏

    user_operation/serializer.py

    class UserFavDetailSerializer(serializers.ModelSerializer):
        '''
        用户收藏详情
        '''
    
        # 通过商品id获取收藏的商品,需要嵌套商品的序列化
        goods = GoodsSerializer()
    
        class Meta:
            model = UserFav
            fields = ("goods", "id")
    

    views.py

    class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
        '''
        list:
            获取用户的所有收藏
        create:
            添加收藏
        destroy:
            取消收藏
        '''
        # permission是用来做权限判断的
        # IsAuthenticated:必须登录用户;IsOwnerOrReadOnly:必须是当前登录的用户
        permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
        # auth使用来做用户认证的
        authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
        # 搜索的字段
        lookup_field = 'goods_id'
    
        def get_queryset(self):
            # 只能查看当前登录用户的收藏,不会获取所有用户的收藏
            return UserFav.objects.filter(user=self.request.user)
    
        # 动态选择serializer
        def get_serializer_class(self):
            if self.action == "list":
                return UserFavDetailSerializer
            elif self.action == "create":
                return UserFavSerializer
            return UserFavSerializer
    

    用户留言功能

    user_operation/serializers.py

    class LeavingMessageSerializer(serializers.ModelSerializer):
        '''
        用户留言
        '''
        # 获取当前登录的用户
        user = serializers.HiddenField(
            default=serializers.CurrentUserDefault()
        )
        # read_only:只返回,post时候可以不用提交,format:格式化输出
        add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')
    
        class Meta:
            model = UserLeavingMessage
            fields = ("user", "message_type", "subject", "message", "file", "id", "add_time")
    

    views.py

    class LeavingMessageViewset(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                                viewsets.GenericViewSet):
        """
        list:
            获取用户留言
        create:
            添加留言
        delete:
            删除留言功能
        """
    
        permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
        authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
        serializer_class = LeavingMessageSerializer
    
        # 只能看到自己的留言
        def get_queryset(self):
            return UserLeavingMessage.objects.filter(user=self.request.user)
    

    urls.py

    # 配置用户留言的url
    router.register(r'messages', LeavingMessageViewset, base_name="messages")
    

    用户收获地址

    user_operation/serializers.py

    class AddressSerializer(serializers.ModelSerializer):
        user = serializers.HiddenField(
            default=serializers.CurrentUserDefault()
        )
        add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')
    
        class Meta:
            model = UserAddress
            fields = ("id", "user", "province", "city", "district", "address", "signer_name", "add_time", "signer_mobile")
    

    views.py

    class AddressViewset(viewsets.ModelViewSet):
        """
        收货地址管理
        list:
            获取收货地址
        create:
            添加收货地址
        update:
            更新收货地址
        delete:
            删除收货地址
        """
        permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
        authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
        serializer_class = AddressSerializer
    
        def get_queryset(self):
            return UserAddress.objects.filter(user=self.request.user)
    

    urls.py

    # 配置收货地址
    router.register(r'address',AddressViewset , base_name="address")
    

    相关文章

      网友评论

          本文标题:Django+Vue打造购物网站(七)

          本文链接:https://www.haomeiwen.com/subject/nxilcqtx.html