当我尝试使用视图中的代码创建新对象时,该对象未创建。没有抛出错误,它只是重新加载页面,但是当我尝试查看数据库时,liquororder 表中不存在任何对象。该代码曾经可以工作,并且类似的代码在我使用它的另一个地方也可以工作,但是我无法弄清楚为什么它在这里不起作用。如果您可能需要任何其他代码,请告诉我。
模型:
class Order(models.Model):
OrderID = models.AutoField(primary_key=True)
storeID = models.ForeignKey(Store)
DateCreated = models.DateField('Date Created', auto_now_add=True)
OrderName = models.CharField('Order Name', max_length=25 )
Active = models.BooleanField()
class LiquorOrder(models.Model):
pack_size = (
('7', '7'),
('7', '7'),
)
LiquorOrderID = models.AutoField(primary_key=True)
storeliquorID = models.ForeignKey(StoreLiquor)
orderID = models.ForeignKey(Order)
OrderAmount = models.PositiveSmallIntegerField('Order Amount', max_length=3, choices=pack_size)
TotalPrice = models.DecimalField('Total Price', max_digits=5, decimal_places=2)
形式:
class AddToOrderForm(forms.ModelForm):
class Meta:
model = LiquorOrder
fields = ('OrderAmount',)
看法:
def storeliquor(request, store_id, liquor_id):
a = Liquor.objects.get(id=liquor_id)
storeliquor = StoreLiquor.objects.get(liquorID=liquor_id)
s = Store.objects.get(StoreID=store_id)
x = Order.objects.get(storeID=s, Active=True)
y = a.OffPremisePrice
c = a.BottleSize
g = request.POST.get('OrderAmount', '')
b = a.PackSize
h = b*2
d = b*3
e = b*4
r = b*5
if c == "1750 ML":
pack_size = (
('1', '1'),
('3', '3'),
(b, b),
(h, h),
(d, d),
(e, e),
(r, r),
)
elif c == "1000 ML":
pack_size = (
('1', '1'),
('3', '3'),
('6', '6'),
(b, b),
(h, h),
(d, d),
(e, e),
(r, r),
)
elif c == "750 ML":
pack_size = (
('1', '1'),
('3', '3'),
('6', '6'),
(b, b),
(h, h),
(c, d),
(e, e),
(r, r),
)
elif c == "375 ML":
pack_size = (
('3', '3'),
('6', '6'),
('12', '12'),
(b, b),
(h, h),
(d, d),
(e, e),
(r, r),
)
elif c == "200 ML":
pack_size = (
('12', '12'),
('24', '24'),
(b, b),
(h, h),
(d, d),
(e, e),
(r, r),
)
else:
pack_size = (
(b, b),
(h, h),
(d, d),
(e, e),
(r, r),
)
if request.method == "POST":
f = AddToOrderForm(request.POST)
updateform = AddLiquorForm(request.POST)
if f.is_valid():
z = f.save(commit=False)
z.TotalPrice = (float(y)) * (float(g))
z.storeliquorID = a
z.orderID = x
z.OrderAmount = g
z.save()
if updateform.is_valid():
liquor = StoreLiquor.objects.get(liquorID=liquor_id)
liquor.StorePrice = request.POST.get('StorePrice', '')
liquor.save()
return HttpResponseRedirect('/stores/get/%s' % store_id)
else:
f = AddToOrderForm()
f.fields['OrderAmount'].choices = pack_size
updateform = AddLiquorForm(
initial={'StorePrice': storeliquor.StorePrice }
)
args = {}
args['liquor'] = a
args['s'] = s
args['form'] = f
args['form2'] = updateform
return render(request,'storeliquor.html', args)
出现在 HTML 中的表单:
<form action="/stores/storeliquors/{{ s.StoreID }}/{{ liquor.id }}/" method="post">{% csrf_token %}
<ul>
{{form.as_p}}
</ul>
<input type="submit" name="submit" value="Add to Order">
</form>