我有一个非常简单的Django杂货清单应用程序,我正在使用该应用程序来学习框架,并且我正在使用modelformset来显示/编辑/添加列表中的项目。我遇到的问题是,当我尝试将更改发布到表单集时,它失败了.is_valid()条件。 formset.errors响应为 [{'id':['此字段为必填项。']},{}] ,但是所有文档/网络知识都说不要与自动生成的id字段混淆,因此我不确定为什么它不起作用/为什么没有生成ID字段。
models.py
from django.db import models
# Create your models here.
class Grocery(models.Model):
itemName = models.CharField(max_length=64)
itemQuantity = models.IntegerField()
itemChecked = models.BooleanField(default = False, blank = False, null = False)
forms.py
from django.forms import ModelForm
from .models import Grocery
class GroceryForm(ModelForm):
class Meta:
model = Grocery
fields = ['itemName', 'itemQuantity', 'itemChecked']
views.py
from django.shortcuts import render
from django.forms import modelformset_factory
from .models import Grocery
from .forms import GroceryForm
def index(request):
GroceryFormSet = modelformset_factory(Grocery,
form=GroceryForm,
can_order=True,
can_delete=True,
)
formset = GroceryFormSet(request.POST or None)
if request.method == 'POST':
print(formset.errors)
if formset.is_valid():
formset.save()
context = {
'formset': formset,
}
return render(request, "Lister/index.html", context)
index.html
<form method="post" action="">
{% csrf_token %}
{{ formset.management_form }}
<table>
<tr>
<th>Grocery Thing</th>
<th>Quantity</th>
<th>Got it?</th>
<th>Change Order</th>
<th>Delete?</th>
</tr>
{% for form in formset %}
<tr>
<td>{{ form.itemName }}</td>
<td>{{ form.itemQuantity }}</td>
<td>{{ form.itemChecked }}</td>
<td>{{ form.ORDER }}</td>
<td>{{ form.DELETE }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Save Changes" />
</form>
感谢您的帮助。