且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django 模型表单.包括来自相关模型的字段

更新时间:2021-09-12 23:46:52

一个常见的做法是使用 2 个表单来实现您的目标.

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')

  • Student 模型的表格:

    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.