我正在使用Django表单更新项目的数量,虽然在我看来我的所有内容都是正确的,但是当我点击“提交”时,表单实际上并没有更新数量。值得注意的是,我也没有收到任何错误 - 就像表格被接受一样。
在forms.py中:
class ChangeQty(forms.Form):
quantity = forms.IntegerField(label='', min_value=1, widget=forms.NumberInput())
class Meta:
model = Item
fields = 'quantity'
def __init__(self, *args, **kwargs):
super(ChangeQty, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
self.helper.form_id = 'id-exampleForm'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = 'submit'
self.helper.add_input(Submit('submit', 'Update', css_class='btn btn-md btn-primary'))
self.helper.layout = Layout(
Field('quantity', placeholder='Qty'),
)
在cart.py中
def add(self, product, unit_price, quantity):
try:
item = models.Item.objects.get(
cart=self.cart,
product=product,
)
except models.Item.DoesNotExist:
item = models.Item()
item.cart = self.cart
item.product = product
item.unit_price = unit_price
item.quantity = 1
item.save()
else: #ItemAlreadyExists
item.unit_price = unit_price
item.quantity = int(quantity)
item.save()
在views.py
中def specific_qty(request, product_id, quantity):
if request.method == 'POST':
form = ChangeQty(request.POST)
if form.is_valid():
cart = Cart(request)
cart.add(product_id, product.price, form.get('quantity'))
return render_to_response("full_cart.html", dict(cart=Cart(request)), context_instance=RequestContext(request))
else:
form = ChangeQty()
return render(request, 'full_cart.html', {'form': form})
最后,在full_cart.html中:
<li>Quantity:
<form class="col-md-8 col-md-offset-2" action="." method="post">
{% csrf_token %}
<input id="quantity" type="text" name="quantity" value="{{item.quantity}}">
<input class='btn btn-md btn-primary' type="submit" value="Update">
</form>
</li>