Reputation: 200
I try to add a cart process in my ecommerce prject which is built with Python Django Framework. But when i try to check data the visitor is authenticated or not and try to return data from model manager I face a json serializable problem. In Bellow i give you the sample code,
Here is my view file:
from django.shortcuts import render
from .models import Cart
from django.core import serializers
# Create your views here.
def cart_create(user=None):
cart_obj = Cart.objects.create(user=None)
print('New Cart Created')
return cart_obj
def cart_home(request):
cart_id = request.session.get("cart_id", None)
qs = Cart.objects.filter(id=cart_id)
if qs.count() == 1:
print("Cart Id exists")
cart_obj = qs.first()
if request.user.is_authenticated and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
else:
#cart_obj = cart_create()
cart_obj = Cart.objects.new(user=request.user)
request.session['cart_id'] = cart_obj
return render(request, "carts/home.html")
Here Is my Model File:
from django.db import models
from django.conf import settings
from products.models import Product
from django.core.serializers import serialize
User = settings.AUTH_USER_MODEL
# Create your models here.
class CartManager(models.Manager):
def new(self, user=None):
print(user)
user_obj = None
if user is not None:
if user.is_authenticated:
user_obj = user
return self.model.objects.create(user=user)
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
products = models.ManyToManyField(Product, blank=True)
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = CartManager()
def __str__(self):
return str(self.id)
Here is the generated Error:
I have no idea why generated this error. I have try to many possible ways to solve this problem. But can not solve it . Can anyone help me..
Upvotes: 0
Views: 139
Reputation: 673
Replace line request.session['cart_id'] = cart_obj
with request.session['cart_id'] = cart_obj.id
Upvotes: 1