Reputation: 360
I am developing a cart api where add item in cart and remove. I craete a CartViewSet(viewsets.ModelViewSet) and also create two method in CartViewSet class add_to_cart and remove_from_cart..But when I want to add item in cart using add_to_cart and remove using romve_from_cart method then got HTTP 405 Method Not Allowed.I am beginner in building Django rest api.Please anyone help me. Here is my code:
my configuration:
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))
]
Upvotes: 3
Views: 796
Reputation: 10227
When you create a ModelViewSet for Cart
then your API will be /api/carts/cart_id/add_to_cart
(i.e. cart_id
, not product_id
).
So, I believe you get Not found
error because there is no such a cart with that ID you pass there.
I think your architecture isn't good in the first place. I don't think you should create Cart
and CartItem
models. Items that a user puts into a cart is a temporary data, just store this information in localStorage
on the frontend.
And just have an endpoint to checkout all these selected products: POST /api/checkout/
. Where you'll send product IDs and their quantity.
Upvotes: 3