0

当我尝试将产品添加到购物车时出现此错误。没有尺寸这项工作,但我需要尺寸。那么我能做些什么来解决它呢?

February 11, 2017 - 12:04:30
Django version 1.10.5, using settings 'villain.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[11/Feb/2017 12:04:41] "GET /8/koszulka-moro/ HTTP/1.1" 200 3624
Internal Server Error: /cart/add/8/
Traceback (most recent call last):
  File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/views/decorators/http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "/home/krystian/Project/villain/villain/cart/views.py", line 19, in cart_add
    update_size=cd['size_update']
  File "/home/krystian/Project/villain/villain/cart/cart.py", line 34, in add
    self.cart[product_id]['size'] += size
KeyError: 'size'

这就是我的购物车.py

class Cart(object):
    def __init__(self, request):
        """

         Inicjaliazacja koszyka na zakupy.
        """
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            # pusty koszyk w sesji
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, quantity=1, update_quantity=False, update_size=False, size=None):
        """
         Dodanie produktu i zmiana ilości
        """
        product_id = str(product.id)
        if product_id not in self.cart:
            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
        if update_size:
            self.cart[product_id]['size'] = size
        else:
            self.cart[product_id]['size'] += size
        self.save()

    def save(self):
        self.session[settings.CART_SESSION_ID] = self.cart
        self.session.modified = True

    def remove(self, product):
        """
        Usunięcie produktów z koszyka
        """
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def __iter__(self):
        """
        Iteracja przez elementy na zakupy i pobranie z bazy danych
        """

        product_ids = self.cart.keys()
        products = Product.objects.filter(id__in=product_ids)
        for product in products:
            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):
        """
        Obliczanie liczby wszytskich elementów w koszyku.
        """
        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):
        # usunięcie koszyka
        del self.session[settings.CART_SESSION_ID]
        self.session.modified = True

这是我的forms.py

PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]

SIZE_CHOICES = (
    ('S', 'S'),
    ('M', 'M'),
    ('L', 'L'),
    ('XL', 'XL')
)


class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(
                                choices=PRODUCT_QUANTITY_CHOICES,
                                coerce=int)
    update = forms.BooleanField(required=False,
                                initial=False,
                                widget=forms.HiddenInput)
    size = forms.TypedChoiceField(
                                choices=SIZE_CHOICES)
    size_update = forms.BooleanField(required=False,
                                     initial=False,
                                     widget=forms.HiddenInput)

这是我的意见.py

@require_POST
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.cleaned_data
        cart.add(product=product,
                 quantity=cd['quantity'],
                 update_quantity=cd['update'],
                 size=cd['size'],
                 update_size=cd['size_update']
                 )
    return redirect('cart:cart_detail')


def cart_remove(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    cart.remove(product)
    return redirect('cart:cart_detail')


def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
                      initial={'quantity': item['quantity'],
                               'update': True})
        item['update_size_form'] = CartAddProductForm(
                      initial={'size': item['size'],
                               'size_update': True}
        )
    return render(request,
                  'cart/detail.html',
                  {'cart': cart})

我尝试修复它,但我的所有尝试都不起作用。

4

1 回答 1

0

您只用数量和价格初始化产品字典。如果您希望能够更新大小,则应该在该初始化中包含一个大小值。

于 2017-02-11T13:21:39.863 回答