Initialize TypedChoiceField field form dynamically

时间:2018-06-04 16:42:31

标签: python django

I need help on how to initialize a django form field, depending on a specific object.

The context is: I would like to show the maximum stock of a product to add the shopping cart.

forms.py

class ShoppingCartForm(forms.Form):
    quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, help_text = 'Uds.')

models.py

@autoconnect
class Product(models.Model):
    category = models.ForeignKey(ShopCategory)
    name = models.CharField(max_length=100, db_index=True, unique=True)
    slug = models.SlugField(max_length=100, db_index=True, unique=True, blank=True)
    description = models.CharField(max_length=500, blank=True)
    updated_date = models.DateTimeField(auto_now_add=True)
    created_date = models.DateTimeField(auto_now=True)
    stock = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
    # images

    class Meta:
        verbose_name = 'product'
        verbose_name_plural = 'products'

    def __unicode__(self):
        return self.name

    def pre_save(self):
        self.slug = self.name.replace(' ', '_').lower()

views.py

def product_list(request, shop_category_slug=None):
    category = None
    products = shop_models.Product.objects.filter(stock__gte=1)

    if shop_category_slug:
        category = get_object_or_404(shop_models.ShopCategory, slug=shop_category_slug)
        products = products.filter(category=category)

    if request.method == 'POST':
        shop_filter_form = shop_forms.ProductFilter(request.POST)
        products = products.filter(
        category=shop_filter_form.cleaned_data['category'],
        name__contains=shop_filter_form.cleaned_data['name'])
    else:
        shop_filter_form = getShopFilter(request)

    return render(request, 'product_list.html', {
        'category': category,
        'products': products.order_by("-created_date"),
        'categories': getShopCategories(),
        'shop_filter_form': shop_filter_form,
        'shoppingcart_form': getShoppingCart(),
    })

0 个答案:

没有答案