我想更新现有的表单集,但是当我尝试保存数据时,出现验证问题,请提供帮助。 我对该表单集的模型为:
class ProductforOrder(models.Model):
order=models.ForeignKey(Order,on_delete=models.CASCADE)
order_product=models.ForeignKey(Product,on_delete=models.PROTECT)
order_count=models.IntegerField(default=1)
,表单字段为:
class PoroductforOrderform(forms.ModelForm):
class Meta:
model = ProductforOrder
fields = [ f.name for f in ProductforOrder._meta.fields ]
fields.remove('order')
创建的格式集为:
orderformset = modelformset_factory(ProductforOrder,form=PoroductforOrderform,extra=0)
formobj = Order.objects.get(pk=pk)
form=Orderform(instance=formobj)
formsetobj = ProductforOrder.objects.filter(order=formobj)
formset = orderformset( queryset=formsetobj)
print(formset.is_valid())
这给了我“ False”,我无法更新表单集。 请帮忙。
答案 0 :(得分:0)
在没有看到模板文件的情况下,我将猜测您是在单独渲染表单字段而不是仅使用表单。例如,在您的模板中,您有类似的内容:
private void DeleteBtn_Click(object sender, EventArgs e)
{
bool selected = false;
int SelectColumnIndex = 0;
string data = string.Empty;
foreach (DataGridViewRow row in dgCorp.Rows)
{
if (Convert.ToBoolean(row.Cells[0].Value) == true)
{
selected = true;
int MaCopr = Convert.ToInt32(row.Cells["CorporationNo"].Value.ToString());
if (MessageBox.Show("Are u sure?", "confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
if (Coporration.DeleteCorpByNo(MaCopr))
{
MessageBox.Show("Delete Successful");
RefreshDataGridView();
}
else MessageBox.Show("An Error!");
}
}
if (!selected)
{
MessageBox.Show("You must select one corporation at least");
}
}
在这种情况下,请确保{% for form in formset %}
<p>Please input your name {{ form.name }} and age {{ form.age }}</p>
{% endfor %}
内有{{ form.id }}
for for循环,例如:
for form in formset
答案 1 :(得分:0)
formset.is_valid()
始终返回false,因为您未提供任何数据。
请参阅此链接: formset validation和formset in POST method
所以就您而言,
if request.method == "POST":
formset = orderformset(request.POST, queryset=formsetobj)
if formset.is_valid():
# code for valid formset
else:
# code for invalid formset
print(formset.errors) # to check why your formset is invalid
else:
formset = orderformset(queryset=formsetobj)