Django REST framework+Vue to create a fresh supermarket (8) 9. Personal center function development

Django REST framework+Vue to create a fresh supermarket (8) 9. Personal center function development

9. personal center function development

9.1.drf's api document is automatically generated and

(1)  url

#drf document, title customization
    path('docs',include_docs_urls(title='Legend of Sword and Fairy')),

Visit: http://127.0.0.1:8000/docs can be automatically generated

(2) The advantages of drf files:

  • Automatic generated
  • Interaction and testing can be done in the document
  • Can generate js, shel and python code snippets

(3) The format of comments in the code:

ViewSet format, please see the official document for more

class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    '''
    list:
        Product list, pagination, search, filter, sort
    retrieve:
        Get product details
    '''

(4) Description

There are three ways to add a description of a field:

  • add to the model field
  • serializer field plus
  • You can also add to the filter

9.2. Dynamically set serializer and permission to obtain user information

 Modify the user’s personal information, because the phone number has been verified, so you can’t change it casually

In the member center page, if you want to get personal information, you only need to inherit one more class in UserViewset: mixins.RetrieveModelMixin

 (1) Serialization of user details

users/serializers.py

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

(2) users/views.py

class UserViewset(CreateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    '''
    user
    '''
    serializer_class = UserRegSerializer
    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)
        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)

    #This requires dynamic permission configuration
    #1. User registration should not be restricted
    #2. When you want to get user details, you must log in
    def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []

        return []

    #Here you need to dynamically choose which serialization method to use
    #1.UserRegSerializer (user registration), only returns username and mobile, the member center page needs to display more fields, so create a UserDetailSerializer
    #2. The problem comes again, if the registered userdetailSerializer is used, it will cause the authentication to fail, so the serializer needs to be used dynamically
    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    #Although you can get user details by inheriting Retrieve, you don’t know the user’s id, so you have to rewrite the get_object method
    #Rewrite the get_object method to know which user it is
    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()

Mainly added content:

  • Inherit mixins.RetrieveModelMixin -->>Get user information
  • Rewrite get_object -->>Get the logged-in user
  • get_permissions -->>Dynamic permission assignment
  • get_serializer_class -->>Dynamic serialization allocation

Now you can get the user's information from the database

User personal information modification

 Just add one more inherited mixins.UpdateModelMixin.

class UserViewset(CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,viewsets.GenericViewSet):

9.3. User favorites

(1) User's favorite product details

add in user_operation/serializer.py

class UserFavDetailSerializer(serializers.ModelSerializer):
    '''
    User favorite details
    '''

    #Get the favorite products through the product id, the serialization of nested products is required
    goods = GoodsSerializer()
    class Meta:
        model = UserFav
        fields = ("goods", "id")

(2) user_operation/views.py

Set the serializer dynamically

 #Dynamic selection serializer
    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer
        return UserFavSerializer
# user_operaton/views.py

from rest_framework import viewsets
from rest_framework import mixins
from .models import UserFav
from .serializers import UserFavSerializer,UserFavDetailSerializer
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication

class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
    '''
    User favorites
    '''
    #permission is used to judge permissions
    # IsAuthenticated: Must log in user; IsOwnerOrReadOnly: Must be currently logged in user
    permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    #authUsed for user authentication
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    #Search fields
    lookup_field ='goods_id'

    #Dynamic selection serializer
    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer
        return UserFavSerializer

    def get_queryset(self):
        #Can only view the favorites of the currently logged in user, not all users' favorites
        return UserFav.objects.filter(user=self.request.user)

 In the member center, you can see the favorite products and detailed information, click delete, you can delete the corresponding products

9.4. User message function

(1) user_operation/serializers.py

class LeavingMessageSerializer(serializers.ModelSerializer):
    '''
    User Comments
    '''
    # Get the currently logged-in user
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    #read_only: Only return, no need to submit when post, format: formatted output
    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")

(2) user_operation/views.py

class LeavingMessageViewset(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                            viewsets.GenericViewSet):
    """
    list:
        Get user message
    create:
        Add message
    delete:
        Delete message function
    """

    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = LeavingMessageSerializer

    # Can only see my own comments
    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)

(3) Configure url

# Configure the url of the user's message
router.register(r'messages', LeavingMessageViewset, base_name="messages")

 Can get, delete messages and other functions

9.5. User harvest address

 (1) 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")

(2) user_operation/views.py

If you want to add, delete, modify, and check, you just need to inherit ModelViewSet.

class AddressViewset(viewsets.ModelViewSet):
    """
    Delivery address management
    list:
        Get shipping address
    create:
        Add shipping address
    update:
        Update shipping address
    delete:
        Delete shipping address
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)

(3) Configure url

# Configure the delivery address
router.register(r'address',AddressViewset, base_name="address")
Reference: https://cloud.tencent.com/developer/article/1097931 Django REST framework+Vue to build a fresh supermarket (8) 9. Personal center function development-cloud + community-Tencent Cloud