How to have a nested inline formset within a form in Django?

14,180

Of course it's possible - how do you think the admin does it?

Take a look at the inline formsets documentation.

Edited after comment Of course, you need to instantiate and render both the parent form and the nested formset. Something like:

def edit_contact(request, contact_pk=None):
    if contact_pk:
        my_contact = Contact.objects.get(pk=contact_pk)
    else:
        my_contact = Contact()
    CommunicationFormSet = inlineformset_factory(Contact, Communication)
    if request.POST:
        contact_form = ContactForm(request.POST, instance=my_contact)
        communication_set = CommunicationFormSet(request.POST,
                                                 instance=my_contact)
        if contact_form.is_valid() and communication_set.is_valid():
            contact_form.save()
            communication_set.save()
    else:
        contact_form = ContactForm(instance=my_contact)
        communication_set = CommunicationFormSet(instance=my_contact)
 
    return render_to_response('my_template.html', 
                              {'form': contact_form, 'formset':communication_set})

and the template can be as simple as:

<form action="" method="POST">
  {{ form.as_p }}
  {{ formset }}
</form>

although you'll probably want to be a bit more detailed in how you render it.

Share:
14,180

Related videos on Youtube

Marc-Antoine Lemieux
Author by

Marc-Antoine Lemieux

Updated on March 10, 2021

Comments

  • Marc-Antoine Lemieux
    Marc-Antoine Lemieux about 3 years

    I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects.

    For example, I have a Contact model

    class Contact(models.Model):
        ...
    


    And a Communication model

    class Communication(models.Model):
       contact = models.ForeignKey(Contact)
    


    and I want to have a form for Contact with a inline formset nested in it for managing communications related to it.

    Is it possible to do so with existing components or do I have a hopeless dream?

    EDIT : I know that the admin panel does it, but how do I make work in a view?

  • Marc-Antoine Lemieux
    Marc-Antoine Lemieux about 13 years
    Thanks for the quick answer, but I tried it and when I render the formset, there are only lines for the related objects. I need the Contact form AND the Communication Inline formset. I know that the admin panel does it, but how do I make work in a view?
  • Bahman Rouhani
    Bahman Rouhani over 6 years
    is there any way to add the formset into the main form? for some reasons I can have a single modelform only and I need a inlineformset inside it.
  • Brian Olpin
    Brian Olpin over 5 years
    The link to 'inline formsets documentation' produces a 404 error

Related