我有一个这个模型:
class Fleet(models.Model):
company = models.ForeignKey("Company", editable=False)
aircraft = models.ForeignKey("Aircraft")
size = models.IntegerField(default=1)
description = models.TextField(blank=True)
def __unicode__(self):
return u"%s" % (self.aircraft, )
然后是基于此模型的表单:
class FleetForm(ModelForm):
class Meta:
model = Fleet
exclude = ('company', )
当我在模板中使用此表单时,不会添加“公司”字段,这是预期的。但该字段必须为空白!=真。
我使用此表单的方式,公司属性将始终在视图函数中已知,因为它是从URL传递的。在保存之前,如何将公司添加到视图功能中的表单?
以下是我的观点:
def new_fleet(request, company_id):
from forms import FleetForm
company = Company.objects.get(pk=company_id)
if request.method == "POST":
form = FleetForm(request.POST,)
form.company = company #doesn't work
form = form.save(commit=False) #can't do this because the form
form.company = company #doesn't validate (company is not set)
if not form.errors:
form.save()
else:
fleet = Fleet(company=company) #pointless because the company widget
form = FleetForm(instance=fleet) #isn't created but eh whatever
答案 0 :(得分:9)
有两种方法可以解决这个问题:
使用缺少但必填字段的初始值实例化您的模型:
company = Company.objects.get(pk=company_id)
fleet = Fleet(company=company)
form = FleetForm(request.POST, instance=fleet)
new_fleet = form.save()
使用save(commit=False)
并手动设置任何额外的必填字段:
company = Company.objects.get(pk=company_id)
form = FleetForm(request.POST)
fleet = form.save(commit=False)
fleet.company = company
new_fleet = fleet.save()
有关详情,请参阅this section of the ModelForm API documentation中的说明。
顺便说一下,editable=False
或exclude
足以从ModelForm
删除字段;你不需要两者。
答案 1 :(得分:1)