我尝试在表单中显示新供应商的字段,但它有错误'供应商'对象没有属性'id'。这个错误的原因是什么?
Models.py
## Parent class
class Person(models.Model):
last_name = models.CharField(max_length=256)
first_name = models.CharField(max_length=256)
company_name = models.CharField(max_length=256)
....
class Meta:
abstract = True
## Child class
class Supplier(Person):
def __init__(self):
pass
forms.py:
class SupplierNewForm(forms.ModelForm):
class Meta:
model = Supplier
views.py:
def SupplierNew(request):
if request.method == "POST":
## Save post data
s = Supplier()
supplier_form = SupplierNewForm(instance=s) `Error will occur here...`
return render(request, "supplier_new.html", {
'supplier_form' : supplier_form,
})
答案 0 :(得分:0)
您不必为新表单发送实例。问题是,django期望instance
是一个已经存在于数据库中的对象,但是找不到它。现在,当您处理request.POST
中的代码时,将为您创建一个新对象。
所以,只需改变
s = Supplier()
supplier_form = SupplierNewForm(instance=s)
到
supplier_form = SupplierNewForm()
我还会重新考虑视图方法的流程:
def SupplierNew(request):
if request.method == "POST":
## Save post data
else:
supplier_form = SupplierNewForm()
return render(request, "supplier_new.html", {
'supplier_form' : supplier_form,
})
通过放置else
,如果表单提交有错误,您可以重新呈现到同一模板,并且可以向最终用户显示表单错误。