Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

595
Views
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 Courses with their corresponding details, and to each Course add any number of Students, how could this be done? I am aware of ModelForms, 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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!