只需将 HouseForm 粘贴到 PersonForm 中,将其作为 clean() 过程的一部分进行评估,然后将其保存为 save() 过程的一部分。也可以在模型集中工作。
class HouseForm(forms.modelForm):
""" Edit a house """
class Meta:
model = House
exclude = ()
class PersonForm(forms.ModelForm):
""" Edit a person and her house """
class Meta:
model = Person
exclude = ()
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['house'].required = False
data = kwargs.get('data')
# 'prefix' parameter required if in a modelFormset
self.house_form = HouseForm(instance=self.instance and self.instance.house,
prefix=self.prefix, data=data)
def clean(self):
if not self.house_form.is_valid():
raise forms.ValidationError("House not valid")
def save(self, commit=True):
obj = super(PersonForm, self).save(commit=commit)
obj.house = self.house_form.save()
obj.save()
然后在您的标记中:
<form ...>
{{ person_form }}
{{ person_form.house_form }}
</form>