Django rest框架viewsets方法返回HTTP 405方法不允许

问题描述

我正在开发一个购物车api,在其中添加购物车中的商品并删除。我创建了一个CartViewSet(viewsets.ModelViewSet)并在CartViewSet类的add_to_cart和remove_from_cart中创建了两个方法。但是当我想使用add_to_cart在购物车中添加项目并使用romve_from_cart方法删除时又得到了HTTP 405方法不允许,我是初学者构建Django rest api。请有人帮助我。这是我的代码

我的配置:

Django==3.1.1
djangorestframework==3.12.0

models.py:

from django.db import models
from product.models import Product
from django.conf import settings
User=settings.AUTH_USER_MODEL

class Cart(models.Model):
    """A model that contains data for a shopping cart."""
    user = models.OnetoOneField(
        User,related_name='user',on_delete=models.CASCADE
    )
    created_at = models.DateTimeField(auto_Now_add=True)
    updated_at = models.DateTimeField(auto_Now=True)

class CartItem(models.Model):
    """A model that contains data for an item in the shopping cart."""
    cart = models.ForeignKey(
        Cart,related_name='cart',on_delete=models.CASCADE,null=True,blank=True
    )
    product = models.ForeignKey(
        Product,related_name='product',on_delete=models.CASCADE
    )
    quantity = models.PositiveIntegerField(default=1,blank=True)

    def __unicode__(self):
        return '%s: %s' % (self.product.title,self.quantity)

serializers.py:

from rest_framework import serializers
from .models import Cart,CartItem
from django.conf import settings
from product.serializers import ProductSerializer

User=settings.AUTH_USER_MODEL

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username','email']

class CartSerializer(serializers.ModelSerializer):

    """Serializer for the Cart model."""

    user = UserSerializer(read_only=True)
    # used to represent the target of the relationship using its __unicode__ method
    items = serializers.StringrelatedField(many=True)

    class Meta:
        model = Cart
        fields = ['id','user','created_at','updated_at','items']
            

class CartItemSerializer(serializers.ModelSerializer):

    """Serializer for the CartItem model."""

    cart = CartSerializer(read_only=True)
    product = ProductSerializer(read_only=True)

    class Meta:
        model = CartItem
        fields = ['id','cart','product','quantity']

views.py:

from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.decorators import action

from .serializers import CartSerializer,CartItemSerializer
from .models import Cart,CartItem
from product.models import Product
class CartViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows carts to be viewed or edited.
    """
    queryset = Cart.objects.all()
    serializer_class = CartSerializer

    @action(detail=True,methods=['post','put'])
    def add_to_cart(self,request,pk=None):
        """Add an item to a user's cart.
        Adding to cart is disallowed if there is not enough inventory for the
        product available. If there is,the quantity is increased on an existing
        cart item or a new cart item is created with that quantity and added
        to the cart.
        Parameters
        ----------
        request: request
        Return the updated cart.
        """
        cart = self.get_object()
        try:
            product = Product.objects.get(
                pk=request.data['product_id']
            )
            quantity = int(request.data['quantity'])
        except Exception as e:
            print (e)
            return Response({'status': 'fail'})

        # disallow adding to cart if available inventory is not enough
        if product.available_inventory <= 0 or product.available_inventory - quantity < 0:
            print ("There is no more product available")
            return Response({'status': 'fail'})

        existing_cart_item = CartItem.objects.filter(cart=cart,product=product).first()
        # before creating a new cart item check if it is in the cart already
        # and if yes increase the quantity of that item
        if existing_cart_item:
            existing_cart_item.quantity += quantity
            existing_cart_item.save()
        else:
            new_cart_item = CartItem(cart=cart,product=product,quantity=quantity)
            new_cart_item.save()

        # return the updated cart to indicate success
        serializer = CartSerializer(data=cart)
        return Response(serializer.data,status=200)

    @action(detail=True,'put'])
    def remove_from_cart(self,pk=None):
        """Remove an item from a user's cart.
        Like on the Everlane website,customers can only remove items from the
        cart 1 at a time,so the quantity of the product to remove from the cart
        will always be 1. If the quantity of the product to remove from the cart
        is 1,delete the cart item. If the quantity is more than 1,decrease
        the quantity of the cart item,but leave it in the cart.
        Parameters
        ----------
        request: request
        Return the updated cart.
        """
        cart = self.get_object()
        try:
            product = Product.objects.get(
                pk=request.data['product_id']
            )
        except Exception as e:
            print (e)
            return Response({'status': 'fail'})

        try:
            cart_item = CartItem.objects.get(cart=cart,product=product)
        except Exception as e:
            print (e)
            return Response({'status': 'fail'})

        # if removing an item where the quantity is 1,remove the cart item
        # completely otherwise decrease the quantity of the cart item
        if cart_item.quantity == 1:
            cart_item.delete()
        else:
            cart_item.quantity -= 1
            cart_item.save()

        # return the updated cart to indicate success
        serializer = CartSerializer(data=cart)
        return Response(serializer.data)

class CartItemViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows cart items to be viewed or edited.
    """
    queryset = CartItem.objects.all()
    serializer_class = CartItemSerializer

urls.py:

from django.urls import path,include
from rest_framework import routers

from .views import (CartViewSet,CartItemViewSet)

router = routers.DefaultRouter()
router.register(r'carts',CartViewSet)
router.register(r'cart_items',CartItemViewSet)

urlpatterns = [
    path('',include(router.urls))
]

解决方法

Cart创建ModelViewSet时,您的API将为/api/carts/cart_id/add_to_cart(即cart_id,而不是product_id)。

因此,我相信您会遇到Not found错误,因为没有这样的带有您传递的ID的购物车。

我认为您的架构一开始就不好。我认为您不应该创建CartCartItem模型。用户放入购物车中的物品是临时数据,只需将此信息存储在前端的localStorage中即可。

,只有一个端点可以签出所有这些选定的产品:POST /api/checkout/。您将在何处发送产品ID及其数量。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...