TypeError:<product:tablet =“”>不是JSON可序列化的

时间:2016-04-18 01:08:11

标签: json django session typeerror cart

我正在尝试使用django实现购物车应用程序(来自django,例如第7章)。但是从我的产品列表中,当我点击添加到购物车时,我应该被带到购物车详细信息(detail.html模板)页面而不是我收到错误<Product: Tablet> is not JSON serializable 我使用以下cart.py文件。怀疑错误来自__iter__方法。请帮忙

cart.py

from django.conf import settings

from resource_manager.models import Product


class Cart(object):
    def __init__(self, request):
        """
        Initialize the cart.
        """
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            # save an empty cart in the session
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, quantity=1, update_quantity=False):
        """
        Add a product to the cart or update its quantity.
        :param product:
        :param quantity:
        :param update_quantity:
        :return:
        """

        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0}
            # self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity
        self.save()

    def save(self):
        # update the session cart
        self.session[settings.CART_SESSION_ID] = self.cart
        # mark the session as "modified" to make sure it is saved
        self.session.modified = True

    def remove(self, product):
        """
        Remove a product from the cart.
        :param product:
        :return:
        """
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
        self.save()

    def __iter__(self):
        """
        Iterate over the items in the cart and get the products
        from the database.
        """
        product_ids = self.cart.keys()
        # get the product objects and add them to the cart
        products = Product.objects.filter(id__in=product_ids)
        for product in products:
            self.cart[str(product.id)]['product'] = product

        # self.cart[str(product.id)]['product'] = product
        for item in self.cart.values():
            # item['price'] = Decimal(item['price'])
            # item['total_price'] = item['price'] * item['quantity']
            yield item

    def __len__(self):
        """
        Count all items in the cart.
        """
        return sum(item['quantity'] for item in self.cart.values())

    # def get_total_price(self):
    #     return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

    def clear(self):
        # remove cart from session
        del self.session[settings.CART_SESSION_ID]
        self.session.modified = True

这是Product模型

class Product(models.Model):

    NAME_CHOICES = (
        ('Radio', 'Radio'),
        ('Tablet', 'Tablet'),
        ('Mat', 'Mat'),
        ('Workbook', 'Workbook'),
    )
    name = models.CharField(max_length=15, choices=NAME_CHOICES, unique=True)
    image = models.ImageField(upload_to='resource_manager/%Y/%m/%d', blank=True)
    # available = models.BooleanField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    @property
    def is_available(self):
        if self.stock_count > 0:
            available = True
        else:
            available = False
        return available

    @property
    def stock_count(self):
        count = Equipment.objects.filter(equipment_type=self.name).count()
        return count

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('resource_manager:product_detail',
                       args=[self.pk])

0 个答案:

没有答案