Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

596
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda