Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
how to add a different model form to modelformset_factory

With respect to these models:

class Projects(models.Model):
    projectDescription = models.CharField(max_length=50,blank=True,null = True,)
    status = models.IntegerField(choices = Status_CHOICES, default = 4)
    projectOwner = models.ForeignKey(staff, on_delete=models.CASCADE, blank=True,null = True,)

class Updates(models.Model):
    project = models.ForeignKey(Projects, on_delete=models.CASCADE)
    update = models.CharField(max_length=50,blank=True,null = True,)
    updateDate = models.DateTimeField(default = timezone.now, editable = False)
    addedBy = models.CharField(max_length=35,blank=True,)

I want to create a view that displays forms for all of the current projects. This is easy using a modelformset_factory. But how can I also add an additional form to each of these project form instances so that an Update to the project (foreign key) can be made? Ideally the user makes changes to various projects, adds an update to one or several projects, then submits the form to save all the changes. What I have below seems to be very close, but it is saving an update to each project with the value of whatever I typed into the last form. Which seems to be because the form is not unique. I went down the road of using prefix's which didn't seem to get me anywhere either. help!

update form

class updateForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(updateForm, self).__init__(*args, **kwargs)
    class Meta:
        model = Updates
        fields = ('update',)

view:

def MDSprojects(request):
    projects = Projects.objects.filter(dept = 'Assistive Technology')
    projectFormset = modelformset_factory(Projects, form=EditProjectForm, extra = 0)

    if request.method == 'POST':
        formsetA = projectFormset(request.POST,request.FILES)
        if formsetA.is_valid():
            for f in formsetA:
                formA = f.save(commit = False)
                id = formA.id
                formA.save()
                formsetB = updateForm(request.POST,request.FILES)
                if formsetB.is_valid():
                    formB = formsetB.save(commit = False)
                    project = Projects.objects.get(id = id)
                    formB.project = project
                    formB.save()
                else:
                    print(formsetB.errors)
            return redirect('MDS_Projects')
        else:
            print(formsetA.errors)
    else:
        formsetA = projectFormset(queryset = projects)
        formsetB = updateForm()
        return render(request,'MDSprojectsB.html',{'formset':formsetA,'formsetB':formsetB,})

Template:

<form method="POST" enctype= multipart/form-data>
  {{ formset.management_form }}
  {% csrf_token %}
  {%for form in formset%}
    {{ form.management_form }}
    {% for hidden in form.hidden_fields %}
      {{ hidden }}
    {% endfor %}
  <div class="card border-primary mb-3" style="max-width: 85rem;">
    <div class="card-header text-primary">
       <strong>{{form.instance.projectDescription}}</strong>
    </div>
    <div class="card-body text-primary"> Project Name: {{form.projectDescription}}</div>
    <div class="card-body text-primary"> Status: {{form.status}}</div>
    <div class="card-body text-primary"> Status: {{form.projectOwner}}</div>
    <div class="card-body text-primary"> Status: {{form.priority}}</div>
    <div>
        {{ formsetB.management_form }}
        {% for hidden in formsetB.hidden_fields %}
          {{ hidden }}
        {% endfor %}
        {{formsetB}}
    </div>
  </div>
  {% endfor %}
  <button class="btn btn-success btn" type="submit">Save Changes</button>
 </form>

EDIT:

Perhaps another way of explaining my question is:

If I had the same models as above:

class Projects(models.Model):
    projectDescription = models.CharField(max_length=50,blank=True,null = True,)
    status = models.IntegerField(choices = Status_CHOICES, default = 4)
    projectOwner = models.ForeignKey(staff, on_delete=models.CASCADE, blank=True,null = True,)

class Updates(models.Model):
    project = models.ForeignKey(Projects, on_delete=models.CASCADE)
    update = models.CharField(max_length=50,blank=True,null = True,)
    updateDate = models.DateTimeField(default = timezone.now, editable = False)
    addedBy = models.CharField(max_length=35,blank=True,)

I want to have a view that renders all of the current projects as individual forms so that the user can make changes to the project model in one view. Additionally I want the user to be able to add an update to each project as well.

So for example, if I had 3 projects, I would expect to see 3 forms on the page. Each form would contain the fields to modify this project (so these form fields would be pre-populated with the current values). Then lastly (the part I'm stuck on) would be an additional empty field to add an update to the project.

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda