我错过了什么来得到这个错误:<cart:22 =“”>不是JSON可序列化的?

时间:2016-03-12 16:35:51

标签: django-models django-templates django-views

美好的一天, 我收到以下错误:不是JSON可序列化

但我不确定为什么我会得到它。一切都工作正常,直到我决定开始使用会话启动我的用户购物车添加和删除项目 这是我的观点:

def add_or_update_cart(request, slug):
    request.session.set_expiry(180)
    new_total = 0.00
    try:
        # check that session exists
        the_cart_id = request.session['cart_id']
    except:
        new_cart_id = Cart()
        new_cart_id.save()
        request.session['cart_id'] = new_cart_id
        the_cart_id = new_cart_id.id

    cart = Cart.objects.get(id=the_cart_id)
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        pass
    except:
        pass

    if not product in cart.products.all():
        cart.products.add(product)
    else:
        cart.products.remove(product)

    for item in cart.products.all():
        new_total += float(item.price)

    request.session['items_total'] = cart.products.count()
    cart.total = new_total
    cart.save()
    print(cart.products.count())
    return HttpResponseRedirect(reverse('cart:cart'))

型号:

class Cart(models.Model):
    products = models.ManyToManyField(Product, null=True, blank=True)
    total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    cart_status = models.BooleanField(default=False)

    def __str__(self):
        return '%s' % self.id

    def item_name(self):
        return " ".join([str(p) for p in self.product.all()])

并在我的模板中:

<li role="presentation"><a href="{% url 'cart:cart' %}">Cart <span class="badge">{{ request.session.items_total }}</span></a></li>

追溯:

Internal Server Error: /my-cart/puma/
Traceback (most recent call last):
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/handlers/base.py", line 235, in get_response
    response = middleware_method(request, response)
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/middleware.py", line 50, in process_response
    request.session.save()
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 82, in save
    obj = self.create_model_instance(data)
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 68, in create_model_instance
    session_data=self.encode(data),
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/base.py", line 88, in encode
    serialized = self.serializer().dumps(session_dict)
  File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/signing.py", line 95, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Cart: 31> is not JSON serializable

我将不胜感激。

1 个答案:

答案 0 :(得分:1)

当Django尝试在此处序列化模型实例时出现错误

request.session['cart_id'] = new_cart_id

new_cart_id是一个模型实例,无法序列化 您似乎想要将实例的主键分配给键cart_id。

request.session['cart_id'] = new_cart_id.id