Django REST framework+Vue to build a fresh supermarket (7) 8. Product detail page function

Django REST framework+Vue to build a fresh supermarket (7) 8. Product detail page function

8. Product details page function

 8.1.viewsets implements the product detail page interface

(1) The product detail page only needs to inherit one more class (mixins.RetrieveModelMixin).

class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet):

 (2) Commodity Carousel Picture

The commodity carousel diagram is a foreign key, and the serialized foreign key is implemented in a nested method

#Carousel
class GoodsImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsImage
        fields = ("image",)

#Product List Page
class GoodsSerializer(serializers.ModelSerializer):
    #Overwrite foreign key fields
    category = CategorySerializer()
    #images is related_name="images" set in the database, nesting the carousel image
    images = GoodsImageSerializer(many=True)
    class Meta:
        model = Goods
        fields ='__all__'

8.2. Hot commodity interface implementation

Just add "is_hot" to the filter.

Add "is_hot" to GoodsFilter in goods/filters.py

    class Meta:
        model = Goods
        fields = ['pricemin','pricemax','is_hot']

Set the "is_hot" of the product to True in the background, and then the front end can display it

 8.3. User collection interface implementation

 (1) Serialization

user_operation/serializers.py

# user_operation/serializers.py

from rest_framework import serializers
from user_operation.models import UserFav
from rest_framework.validators import UniqueTogetherValidator

class UserFavSerializer(serializers.ModelSerializer):
    #Get the currently logged-in user
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    class Meta:
        #validateAchieve unique union, a product can only be collected once
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=('user','goods'),
                #message information can be customized
                message="Already favorited"
            )
        ]
        model = UserFav
        #When collecting, you need to return the id of the product, because you must know the id of the product when you cancel the collection
        fields = ("user", "goods",'id')

(2) user_operation/views.py

# user_operaton/views.py

from rest_framework import viewsets
from rest_framework import mixins
from .models import UserFav
from .serializers import UserFavSerializer

class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
    '''
    User favorites
    '''
    queryset = UserFav.objects.all()
    serializer_class = UserFavSerializer

Description: Inherited class

  •  mixins.CreateModelMixin Add collection (equivalent to creating a database)
  •  mixins.DestroyModelMixin cancel delete (equivalent to database delete)
  •  mixins.ListModelMixin Get a list of favorite products

 (3) Configure url

# Configure user favorite url
router.register(r'userfavs', UserFavViewset, base_name="userfavs")

Test code:

Visit address: http://127.0.0.1:8000/userfavs/, bookmark three products, check the favorite list

 Repeated collection of a product will prompt "have been collected"

8.3. drf authentication

(1) Custom permissions

Create permissions.py under the utils folder, the code is as follows:

This official website has examples, just copy it directly, and change the owner to user.

# utils/permissions.py

from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        #obj is equivalent to the model in the database, here we need to change the owner to the user in our database
        return obj.user == request.user

(2) user_operation/views

# user_operaton/views.py

from rest_framework import viewsets
from rest_framework import mixins
from .models import UserFav
from .serializers import UserFavSerializer
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
    '''
    serializer_class = UserFavSerializer
    #permission is used to judge permissions
    # IsAuthenticated: Must log in user; IsOwnerOrReadOnly: Must be currently logged in user
    permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    #authUse for user authentication
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    #Search field
    lookup_field ='goods_id'

    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)

Description:

  • Only logged in users can bookmark
  • Users can only get their own favorites, not all users' favorites
  • JSONWebTokenAuthentication authentication should not be configured globally, because the user does not need this authentication when obtaining product information or other pages, so this authentication can be added locally
  • Delete'rest_framework_jwt.authentication.JSONWebTokenAuthentication' in settings,

8.4. User collection function and vue joint debugging 

Modified to local_host

//Collection
export const addFav = params => {return axios.post(`${local_host}/userfavs/`, params)}

//Uncollect
export const delFav = goodsId => {return axios.delete(`${local_host}/userfavs/`+goodsId+'/')}

export const getAllFavs = () => {return axios.get(`${local_host}/userfavs/`)}

//Determine whether to collect
export const getFav = goodsId => {return axios.get(`${local_host}/userfavs/`+goodsId+'/')}
  • Delete favorites: According to the product'goods_id'
  • The items that have been favorited are displayed as "favorites", and those that are not favorited are displayed as "favorites"
Reference: https://cloud.tencent.com/developer/article/1097991 Django REST framework+Vue to create a fresh supermarket (7) 8. Product detail page function-Cloud + Community-Tencent Cloud