如何在 django 中创建与另一个模型一对一关系的模型表单 [英] How can create a model form in django with a one-to-one relation with another model
本文介绍了如何在 django 中创建与另一个模型一对一关系的模型表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个与另一个模型具有一对一关系的模型表单.即模型 1 与模型 2 具有一对一的关系.我希望我的表单显示来自 Model1 和 Model2 的所有字段.还有在视图中显示此内容的最佳方式是什么.
I want to create a model form with a one-to-one relation with another model. i.e Model1 has a one-to-one relation with Model2. I want my form to show all the fields from Model1 as well as Model2. Also what is the best way to show this in a view.
推荐答案
您无需为两个模型创建单个表单.使用两个 django 表单并将它们放在单个 标签中:
You don't need to create the single form for two models. Use two django forms and place them inside the single <form>
tag:
class Model1Form(forms.ModelForm):
class Meta:
model = Model1
class Model2Form(forms.ModelForm):
class Meta:
model = Model2
exclude = ('model1_one_to_one_field', )
def create_models(request):
if request.method == 'POST':
form1 = Model1Form(request.POST)
form2 = Model2Form(request.POST)
if all([form1.is_valid(), form2.is_valid()]):
model1 = form1.save()
model2 = form2.save(commit=False)
model2.model1_one_to_one_field = model1
model2.save()
return redirect('create_models_success')
else:
form1 = Model1Form()
form2 = Model2Form()
return render(request, 'create_models.html',
{'form1': form1, 'form2': form2})
然后是 create_models.html
模板:
<form action="." method="POST">
{% csrf_token %}
{{ form1.as_p }}
{{ form2.as_p }}
<button type="submit">Submit</button>
</form>
这篇关于如何在 django 中创建与另一个模型一对一关系的模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文