Django cart. Не отображается выбор количества товара при добавлении в корзину

  1. Я пытаюсь создать корзину покупок для интернет-магазина. На странице товара отображается кнопка добавить в корзину, но нет кнопки для выбора количества товара. Никак не пойму, что в коде криво, т.к. сравнивал несколько человек.

cart/views:

from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from onlineshop.models import Product
from .cart import Cart
from .forms import CartAddProductForm


@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'])
    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})
    return render(request, 'cart/detail.html', {'cart': cart})

onlineshop/views:

def product_detail(request, product_slug):
    product = get_object_or_404(Product, slug=product_slug, available=True)
    cart_product_form = CartAddProductForm()
    return render(request, 'onlineshop/product.html', {'product': product, 'cart_product_form': cart_product_form})

cart:

from decimal import Decimal
from django.conf import settings
from onlineshop.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):
        product_ids = self.cart.keys()
        products = Product.objects.filter(id__in=product_ids)

        cart = self.cart.copy()
        for product in products:
            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):
        return sum(item['quantity'] for item in self.cart.values())

    def add(self, product, quantity=1, update_quantity=False):
        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
        self.save()

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

    def remove(self, product):
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

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

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

forms:

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)

detail.html: корзина

{% extends "onlineshop/base.html" %}
{% load static %}

{% block title %}
  Корзина покупок
{% endblock %}

{% block content %}
  <h1>Корзина покупок</h1>
  <table class="cart">
    <thead>
      <tr>
        <th>Картинка</th>
        <th>Товар</th>
        <th>Обновить кол-во</th>
        <th>Удалить</th>
        <th>Кол-во</th>
        <th>Цена за шт</th>
        <th>Общая стоимость</th>
      </tr>
    </thead>
    <tbody>
      {% for item in cart %}
        {% with product=item.product %}
          <tr>
            <td>
              <a href="{{ product.get_absolute_url }}">
                <img src="{% if product.image %}{{ product.image.url }}
                {% else %}
                {% static 'images/no_image.png' %}
                {% endif %}">
              </a>
            </td>
            <td>{{ product.name }}</td>
            <td>{{ item.quantity }}</td>
            <td>
              <form action="{% url 'cart:cart_add' product.id %}" method="post">
                {{ item.update_quantity_form.stock }}
                {{ item.update_quantity_form.update }}
                <input type="submit" value="Обновить">
                {% csrf_token %}
              </form>
            </td>
            <td><a href="{% url 'cart:cart_remove' product.id %}">Удалить</a></td>
            <td class="num">${{ item.price }}</td>
            <td class="num">${{ item.total_price }}</td>
          </tr>
        {% endwith %}
      {% endfor %}
      <tr class="total">
        <td>Всего</td>
        <td colspan="4"></td>
        <td class="num">${{ cart.get_total_price }}</td>
      </tr>
    </tbody>
  </table>
  <p class="text-right">
    <a href="{% url 'home' %}" class="button light">В магазин</a>
    <a href="#" class="button">Оформить заказ</a>
  </p>
{% endblock %}

product.html: отображения товара

{% extends 'onlineshop/base.html' %}
{% load static %}
{% block content %}
<h1>{{product.firm }} {{ product.name}}</h1>
<div class="product-detail">
{% if product.image %}
<p><img class="img-article-left" src="{{product.image.url}}"></p>
{% endif %}
<h2>
    <a href="{{ product.cat.get_absolute_url }}">{{ product.cat }}</a>
</h2>
<p class="price">{{ product.price }} ₽ </p>
    <form action="{% url 'cart:cart_add' product.id %}" method="post">
        {{ cart_product_form }}
        {% csrf_token %}
        <input type="submit" value="В корзину">
    </form>

{{product.description|linebreaks}}

</div>

{% endblock %}

'''

введите сюда описание изображения

  1. Т.Е. рядом с кнопкой "добавить в корзину" должен быть выбор количества товара
Вернуться на верх