我正在编写小型 django 互联网商店,但遇到了问题。即,我想要打印产品列表(我需要商品 id)以及在同一页面上购买它们的某种形式。
def order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
# POST data processing
return HttpResponseRedirect('/cart/')
else:
form = OrderForm()
# here I would like to also use product_id from POST to generate products
# that have such id
return render(request, 'order.html', {
'form': form, 'products': products,
})
但是当我错误地提交表单时,会调用 OrderForm() 然后我丢失了我的 ID。任何提示如何解决这个问题(也许保留在某个地方)?
编辑:我的商店用于在给定时间租用一些产品,将产品添加到购物车意味着我创建新的对象租用来存储用户预订产品时的信息
模型:
class Rent(models.Model):
product = models.ForeignKey(Product)
paid = models.BooleanField()
begin_date = models.DateField(auto_now=False)
end_date = models.DateField(auto_now=False)
begin_hour = models.IntegerField(max_length=2, default=00)
end_hour = models.IntegerField(max_length=2, default=24)
和订单
class OrderForm(forms.Form):
begin_date = forms.DateField(label='date', required=True,
widget=extras.widgets.SelectDateWidget(years=range(2013, 2015)))
end_date = forms.DateField(required=True, initial=datetime.date.today,
widget=extras.widgets.SelectDateWidget(years=range(2013, 2015)))
begin_hour = forms.ChoiceField(required=True, choices=((str(x), x) for x in range(0, 25)))
end_hour = forms.ChoiceField(required=True, choices=(((str(x)), x) for x in range(0, 25)))