9-1 drf文档的功能
- 开始我文档一直报错,是因为我viewset有写错了,报的错也是viewset里面的
现在好用了,木哈哈
9-2 动态设置serializers和permissions获取用户信息
mixins.RetrieveModelMixin是 对应网址 XXX/id
用一个viewset增删改查
user/views.py
动态serializers,因为在一个viewset中涉及注册,修改,获取,注册当然不能要求登录等权限.所以要分开写serializers,create和获取detail不是一个.
创建是userserializers,获取是userDetailserializers
user/serializers.py
class UserDetailSerializer(serializers.ModelSerializer):
"""
用户详情序列化类
"""
class Meta:
model = User
fields = ("name", "gender", "birthday", "email", "mobile")
- user/views.py
class UserViewset(CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
用户
"""
serializer_class = UserRegSerializer
queryset = User.objects.all()
authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication )
def get_serializer_class(self):
if self.action == "retrieve":
return UserDetailSerializer
elif self.action == "create":
return UserRegSerializer
return UserDetailSerializer
# permission_classes = (permissions.IsAuthenticated, )
def get_permissions(self):
if self.action == "retrieve":
return [permissions.IsAuthenticated()]
elif self.action == "create":
return []
return []
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)
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)
return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
def get_object(self):
return self.request.user
def perform_create(self, serializer):
return serializer.save()
-
运行结果,请求users/2/
这样请求走的是UserDetailSerializer.py
9-4 修改用户信息
- 就是简单的在views里面加入继承的mixins.UpdateModelMixin
接受put请求
9-5 用户收藏功能
用户收藏的serializers里面只返回了id,需要进一步解析货物的其他字段
还是把UserFavViewset分解成两个动作,一个是list,请求所有收藏,需要详细的字段
一个是创建和取消create只需要id和user_id.这样要在UserFavViewset里面做一个判断,来判断分别使用具体的哪个serializers.体现在代码上就是viewset加一个判断,serializers里面加一个detal
- user_operation/views.py
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
list:
获取用户收藏列表
retrieve:
判断某个商品是否已经收藏
create:
收藏商品
"""
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
lookup_field = "goods_id"
def get_queryset(self):
return UserFav.objects.filter(user=self.request.user)
# def perform_create(self, serializer):
# instance = serializer.save()
# goods = instance.goods
# goods.fav_num += 1
# goods.save()
def get_serializer_class(self):
if self.action == "list":
return UserFavDetailSerializer
elif self.action == "create":
return UserFavSerializer
return UserFavSerializer
- user_operation/serializers.py
class UserFavDetailSerializer(serializers.ModelSerializer):
goods = GoodsSerializer()
class Meta:
model = UserFav
fields = ("goods", "id")
运行效果:
9-6 用户留言功能
- urls
#留言
router.register(r'messages', LeavingMessageViewset, base_name="messages")
- 留言功能没有新鲜事情
- 还是view-serializers-url这一套.
- user_operation/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)
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)
- user_operation/serializers.py
class LeavingMessageSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
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")
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")
9-7 收货地址
#收货地址
router.register(r'address', AddressViewset, base_name="address")
- user_operation/serializers.py
class LeavingMessageSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
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")
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")
- user_operation/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)
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)
有点草率的结束了.