如何从模型中撤回选择

时间:2019-05-03 20:51:11

标签: django django-forms

我有一个库存有一定数量的产品模型,我想在购物篮的入口提取此数量。我创建了三种产品,每种都有一个库存,但是有一种,我创建了10个数量,然后尝试在TypedChoiceField>选择中提取。但是我只需要这个产品一个价值。

from django import forms
from shop.models import Product

class CartProductForm(forms.Form):
    product = Product.objects.all()
    quantity = forms.TypedChoiceField(choices=[(i.stock, str(i.stock)) for i in product], coerce=int)
    update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

enter image description here

views.py

def cart_update(request, product_id):
    cart = Cart(request)
    form = CartProductForm(request.POST)
    product = Product.objects.get(id=product_id)

    if form.is_valid():
        cleaned = form.cleaned_data
        cart.add(product=product, quantity=cleaned['quantity'], update_quantity=cleaned['update'])

    return redirect('cart:cart_show')

cart.py

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()

我知道我需要以某种方式传达产品ID并使用

class CartProductForm(forms.Form):
    product = Product.objects.get(stock=product.stock)

请帮我,对不起我的英语

models.py

class Product(models.Model):
        category = models.ForeignKey(Category, on_delete=models.PROTECT)
        subcategory = models.ForeignKey(Subcategory, on_delete=models.PROTECT)
        kind = models.ForeignKey(Kind, on_delete=models.PROTECT)
        name = models.CharField(max_length=200, db_index=True)
        slug = models.SlugField(max_length=200, db_index=True)
        image = models.ImageField(upload_to=upload_location)
        description = models.TextField()
        price = models.IntegerField()
        stock = models.PositiveIntegerField()
        available = models.BooleanField(default=True)

        def __str__(self):
                return self.name

0 个答案:

没有答案