简体   繁体   English

Django 动态嵌套 model forms

[英]Django dynamic nested model forms

Suppose I have the following models, where there is a 1:many relationship from Teacher to Course , and from Course to Student :假设我有以下模型,其中存在从TeacherCourse以及从CourseStudent的 1:many 关系:

class Teacher(Model):
    name = CharField(max_length=64)
    degree = CharField(max_length=64)

class Course(Model):
    title = CharField(max_length=64)
    level = CharField(max_length=64)
    teacher = ForeignKey(Teacher, on_delete=CASCADE)

class Student(Model):
    name = CharField(max_length=64)
    year = CharField(max_length=64)
    course = ForeignKey(Course, on_delete=CASCADE)

If I want to have a "register teacher" page, where a user can input the details of a Teacher , and also be able to add any number of Course s with their corresponding details, and to each Course add any number of Student s, how could this be done?如果我想要一个“注册教师”页面,用户可以在其中输入Teacher的详细信息,还可以添加任意数量的Course及其相应的详细信息,并向每个Course添加任意数量的Student ,这怎么可能呢? I am aware of ModelForm s, which would make constructing a basic form for a single instance of a model rather trivial, but how can I create a form or forms that essentially nests the models within each other, and allows for a dynamic number of Course and Student ?我知道 ModelForm s,这将使为ModelForm的单个实例构建一个基本表单变得相当微不足道,但是我如何创建一个表单或 forms 本质上将模型相互嵌套,并允许动态数量的CourseStudent

For example, within the Teacher form, there is an "add Course" button, that adds another Course form under that Teacher , such that any details entered into it populate a Course that belongs to that Teacher , and then for each Course form, there is an "add Student" button that adds a Student form for a Student that belongs to that Course .例如,在Teacher表单中,有一个“添加课程”按钮,可以在该Teacher下添加另一个Course表单,这样输入的任何详细信息都会填充属于该TeacherCourse ,然后对于每个Course表单,是一个“添加学生”按钮,用于为属于该CourseStudent添加Student表单。 How can I implement this dynamic and nested behavior?我怎样才能实现这种动态和嵌套的行为?

Then if it is possible to make such a form, back on the Python side after the form is submitted, how will the data be organized?那么如果可以做这样一个表格,表格提交后回到Python这边,数据会怎么组织呢? Or in other words, what will indicate to which Course each Student belongs?或者换句话说,什么将指示每个Student属于哪个Course

You should look at Django ModelFormsets, it is used in those cases你应该看看 Django ModelFormsets,它在那些情况下使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM