更新时间:2022-11-26 10:17:55
一种常见的做法是使用两种形式来实现您的目标。
A common practice is to use 2 forms to achieve your goal.
User
模型:
class UserForm(forms.ModelForm):
... Do stuff if necessary ...
class Meta:
model = User
fields = ('the_fields', 'you_want')
学生
模型的表格:
class StudentForm (forms.ModelForm):
... Do other stuff if necessary ...
class Meta:
model = Student
fields = ('the_fields', 'you_want')
在视图中使用这两种形式(用法示例):
Use both those forms in your view (example of usage):
def register(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
student_form = StudentForm(request.POST)
if user_form.is_valid() and student_form.is_valid():
user_form.save()
student_form.save()
在模板中一起渲染表单:
Render the forms together in your template:
<form action="." method="post">
{% csrf_token %}
{{ user_form.as_p }}
{{ student_form.as_p }}
<input type="submit" value="Submit">
</form>
另一种选择是让您将关系从 OneToOne
更改为 ForeignKey
(这完全取决于您和我只需提及它,不推荐它)并使用 inline_formsets
即可达到预期效果。
Another option would be for you to change the relationship from OneToOne
to ForeignKey
(this completely depends on you and I just mention it, not recommend it) and use the inline_formsets
to achieve the desired outcome.