I want to implement shopping cart in Django Rest Framework. I store information about the shopping cart inside the models. I don't want to use a session for this and I want to save it in the database. users must be logged in to create and add products to the cart. But I want users to be able to add the product to the cart without logging into the site.(Implementation of shopping cart for guest users) I would be very grateful if you could guide me. Thanks
My Model :
class Cart(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
My View:
class AddToCartApi(APIView):
serializer_class = AddToCartSerializer
permission_classes = [IsAuthenticated]
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user_id = request.user.id
data = serializer.validated_data
Cart.objects.create(
user_id=user_id,
product_id=data['product_id'],
quantity=data['quantity'],
)
return Response(....)
CodePudding user response:
Well, in scenarios where you want users to add/update the shopping cart without logging :
Solution 1: You have to implement the same in client side i.e. If your client is interacting through web browser you can make use of local/session storage. Later when the user logs in, you can save all information in database.
CodePudding user response:
To create a shopping cart in Django Rest Framework, you can follow these steps:
1)Define a Cart model to store the items in the shopping cart. The model should have fields for the user, product, and quantity. You can also add fields for the subtotal, total, and any other information you need to store.
# carts/models.py
from django.db import models
class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
subtotal = models.DecimalField(max_digits=10, decimal_places=2)
total = models.DecimalField(max_digits=10, decimal_places=2)
2)Create a serializer class for the Cart model to handle the serialization and deserialization of the cart data.
# carts/serializers.py
from rest_framework import serializers
class CartSerializer(serializers.ModelSerializer):
class Meta:
model = Cart
fields = '__all__'
3)Create a viewset and router for the Cart model to handle the API endpoints.
# carts/views.py
from rest_framework import viewsets
class CartViewSet(viewsets.ModelViewSet):
queryset = Cart.objects.all()
serializer_class = CartSerializer
# carts/urls.py
from django.urls import include, path
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'carts', CartViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
4)Implement the API endpoints for adding items to the cart, updating the quantities, and deleting items from the cart. You can use the create, update, and destroy actions of the ModelViewSet to handle these operations.
# carts/views.py
class CartViewSet(viewsets.ModelViewSet):
queryset = Cart.objects.all()
serializer_class = CartSerializer
def create(self, request, *args, **kwargs):
# Create a new cart item
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def update(self, request, *args, **kwargs):
# Update the quantity of an existing cart item
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self