#python #django #django-rest-framework #rest #django-rest-viewsets
#python #django #django-rest-framework #rest #django-rest-viewsets
Вопрос:
Я разрабатываю API корзины, в котором добавляю товар в корзину и удаляю. Я создаю CartViewSet (наборы просмотров.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, 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))
]
Комментарии:
1. К какому URL-адресу вы пытались получить доступ?
2. 127.0.0.1:8000/api/carts/product_id/add_to_cart
3. когда я отправляю запрос put, возвращаю «деталь»: «Не найдено». и не добавляю товар в корзину.
4. Какой у вас был ответ об ошибке?
5. HTTP 404 не найден
Ответ №1:
Когда вы создаете ModelViewSet для Cart
, ваш API будет /api/carts/cart_id/add_to_cart
(т. Е. cart_id
Нет product_id
).
Итак, я полагаю, вы получаете Not found
ошибку, потому что нет такой корзины с тем идентификатором, который вы там передаете.
Я думаю, что ваша архитектура не очень хороша в первую очередь. Я не думаю, что вам следует создавать Cart
CartItem
модели and. Элементы, которые пользователь помещает в корзину, являются временными данными, просто сохраните эту информацию во localStorage
внешнем интерфейсе.
И просто иметь конечную точку для проверки всех этих выбранных продуктов : POST /api/checkout/
. Куда вы будете отправлять идентификаторы продуктов и их количество.
Комментарии:
1. Спасибо за ваш ответ. Я новичок, но я постараюсь изменить свою архитектуру кодирования. И попробуйте использовать localStorage для временных данных.