Python Django rest framework viewsets方法返回HTTP 405方法不允许

Python Django rest framework viewsets方法返回HTTP 405方法不允许,python,django,django-rest-framework,restapi,django-rest-viewsets,Python,Django,Django Rest Framework,Restapi,Django Rest Viewsets,我正在开发一个购物车api,其中在购物车中添加商品并删除。我创建了一个CartViewSet(viewsets.ModelViewSet)并在CartViewSet类中创建了两个方法add_to_cart和remove_from_cart..但是当我想使用add_to_cart和remove_from_cart方法在cart中添加商品时,不允许使用HTTP 405方法。我是构建Django rest api的初学者。请任何人帮助我。这是我的密码: 我的配置: Django==3.1.1 djan

我正在开发一个购物车api,其中在购物车中添加商品并删除。我创建了一个CartViewSet(viewsets.ModelViewSet)并在CartViewSet类中创建了两个方法add_to_cart和remove_from_cart..但是当我想使用add_to_cart和remove_from_cart方法在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, null=True, 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,methods=['post', 'put'])
    def remove_from_cart(self, request, 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

当您为
Cart
创建模型视图集时,您的API将是
/API/carts/Cart\u id/添加到\u Cart
(即
Cart\u id
,而不是
产品\u id

因此,我相信您会得到
未找到
错误,因为没有这样一个带有您传递的ID的购物车

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


只要有一个端点来检查所有这些选定的产品:
POST/api/checkout/
。您将在哪里发送产品ID及其数量。

您尝试访问的URL是什么?当我发送put请求时,返回“详细信息”:“未找到”。不在购物车中添加商品。您得到的错误响应是什么?HTTP 404未找到谢谢您的回答。我是一个初学者,但我会尝试改变我的编码架构。并尝试将localStorage用于临时数据。
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))
]