【发布时间】:2021-01-14 20:34:22
【问题描述】:
我正在开发一个购物车 API,用于在购物车中添加商品并删除。我创建了一个 CartViewSet(viewsets.ModelViewSet) 并在 CartViewSet 类 add_to_cart 和 remove_from_cart 中创建了两个方法。但是当我想使用 add_to_cart 在购物车中添加项目并使用 romve_from_cart 方法删除时,得到了 HTTP 405 Method Not Allowed。我是初学者构建 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
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))
]
【问题讨论】:
-
您尝试访问的 URL 是什么?
-
当我发送 put 请求然后返回“详细信息”:“未找到。”。并且不在购物车中添加商品。
-
您得到的错误响应是什么?
-
HTTP 404 未找到
标签: python django django-rest-framework rest django-rest-viewsets