Reputation: 85
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(....)
Upvotes: 0
Views: 670
Reputation: 387
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.
Upvotes: 1