当我尝试购买一件产品的太多物品时,这就是它的样子: 的 screenshot 怎么解决?谢谢你:))
product_list.py
{% for product in products %}
<li>
<b>{{ product }}</b>
({{ product.quantity }} available)
(price: {{ product.price }})
<form method="post" action=".">
{% csrf_token %}
{{ shop_form.as_p }}
<input type="hidden" id="{{ product.id }}" name="product_id" value={{ product.id }} />
<input type="submit" value="buy"/>
</form>
</li><br>
{% endfor %}
views.py
def product_list(request):
products = Product.objects.all()
if request.method == 'POST':
product_id = request.POST['product_id']
shop_form = ShopForm(data=request.POST, request_product_id=request.POST['product_id'])
if shop_form.is_valid():
quantity = int(request.POST['quantity'])
product = Product.objects.get(id=product_id)
price = int(product.price * quantity)
request.session['koszyk'][product.name] = product.price
request.session['koszyk']['cena'] += price
return redirect('/products')
else:
shop_form = ShopForm()
return render(request,
'product_list.html',
{'shop_form': shop_form, 'products': products})
forms.py
def __init__(self, *args, **kwargs):
self.request_product_id = kwargs.pop('request_product_id', None)
super(ShopForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['id'] = "id_quantity_{0}".format(
self.request_product_id
)
def clean(self):
q = self.cleaned_data['quantity']
request_product_id = self.request_product_id
product_quantity = Product.objects.get(id=request_product_id).quantity
if int(q) > int(product_quantity):
message = "we have only "
raise ValidationError("we have only %s :(" %(product_quantity))
xxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx