Проблема которая встряла мне поперёк горла возможно находится на поверхности, но т.к я новичок в данной области - найти и решить своими силами не получается.
В чём заключается проблема:
При попытке добавить товар в корзину, выскакивает ошибка "list indices must be integers or slices, not str". Этапы её формирования можно посмотреть в трекбэке ниже...
P.S. Серьёзно не пинайте, я в некоторых моментах даже не совсем понимаю что и как работает. Но в общем то я всё и затеял чтобы разобраться.
Если нужно - добавлю любой кусок кода который я упустил и может дать ответ.
Код который по моему должен дать понимание источника проблемы
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'),
url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'),
url(r'^$', views.cart_detail, name='cart_detail'),
]
class Cart(object):
# Добавление товара в корзину пользователя или обновление количества товара
def add(self, product, quantity=1, update_quantity=False):
product_id = int(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': int(product.price),
}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int)
update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.changed_data
cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
return redirect('cart:cart_detail')
Traceback:
File "D:\Projects\python\sportinia_e-landing\venv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)
File "D:\Projects\python\sportinia_e-landing\venv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request)
File "D:\Projects\python\sportinia_e-landing\venv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Projects\python\sportinia_e-landing\venv\lib\site-packages\django\views\decorators\http.py" in inner 40. return func(request, *args, **kwargs)
File "D:\Projects\python\sportinia_e-landing\sportinia_store\cart\views.py" in cart_add 15. cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
Exception Type: TypeError at /cart/add/3/ Exception Value: list indices must be integers or slices, not str