简体   繁体   中英

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 :

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? 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 ?

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 . 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? Or in other words, what will indicate to which Course each Student belongs?

You should look at Django ModelFormsets, it is used in those cases

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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