Поле 'id' ожидало число, но получило 'product_id' django
В моем приложении для электронной коммерции, когда я нажимаю на добавить в корзину, товар попадает в корзину, но когда я нажимаю на корзину, она выдает мне ошибку, что "Поле 'id' ожидало число, но получило 'product_id'". В основном я использую context_processor для передачи информации cart.py в шаблон. Ссылка на корзину из base.html такова:
<div class="navbar-item">
<a href="{% url 'cart' %}" class="button is-dark">Cart {% if cart %}({{cart|length}}){% endif %}</a>
</div>
Field 'id' expected a number but got 'product_id'
мой проект/urls.py является
path('cart/',include("cart.urls")),
мой cart/urls.py является
urlpatterns = [
path('',views.cart_detail, name='cart')
]
мой cart/cart.py является
from django.conf import settings
from product.models import Product
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
for p in self.cart.keys():
self.cart[(p)]['product'] = Product.objects.get(pk=p)
for item in self.cart.values():
item['total_price'] = item['product'].price * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product_id, quantity=1, update_quantity=False):
product_id = str(product_id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 1, 'id': product_id}
if update_quantity:
self.cart[product_id]['quantity'] += int(quantity)
if self.cart[product_id]['quantity'] == 0:
self.remove(product_id)
self.save()
print(self.cart)
def remove(self, product_id):
if product_id in self.cart:
del self.cart[product_id]
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
def get_total_cost(self):
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)
return sum(item['quantity'] * item['product'].price for item in self.cart.values())
мой context_processors.py является
def cart(request):
return {'cart': Cart(request)}
Разве вы не приводите product_id к строке с помощью str(product_id)
? И позже вы передаете его как число, но это все еще строка. В cart.py
и функции add
Ответ: я не очистил куки. Когда я очищаю их, код
измените это:
{'quantity': 1, 'id': product_id}
с этим
{'quantity': 1, 'id': int(product_id)}