[Solved]-Django: Creating an Inline Formset Similar to the Admin Interface

6👍

Here is the answer how to implement inline formsets like in Django admin
http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/
However only CreateWiew is described. If you want to implement also UpdateView you need to do duplicate your code for it with a little tweaks

def get(self, request, *args, **kwargs):
    """
    Handles GET requests and instantiates blank versions of the form
    and its inline formsets.
    """
    self.object = self.get_object()
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    sample_form = SampleFormSet(instance=self.object)
    return self.render_to_response(
        self.get_context_data(form=form,
                              sample_form=sample_form))

def post(self, request, *args, **kwargs):
    """
    Handles POST requests, instantiating a form instance and its inline
    formsets with the passed POST variables and then checking them for
    validity.
    """
    self.object = self.get_object()
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    sample_form = SampleFormSet(self.request.POST, instance=self.object)
    if (form.is_valid() and sample_form.is_valid()):
        return self.form_valid(form, sample_form)
    else:
        return self.form_invalid(form, sample_form)

def form_valid(self, form, sample_form):
    """
    Called if all forms are valid. Creates a Recipe instance along with
    associated Ingredients and Instructions and then redirects to a
    success page.
    """
    self.object = form.save()
    sample_form.save()
    return HttpResponseRedirect(self.get_success_url())

and don`t forget to add DELETE formset field to your template

          {% for form in sample_form %}
          {{ form.id }}
          <div class="inline {{ sample_form.prefix }}">
              {{ form.description.errors }}
              {{ form.description.label_tag }}
              ...
              {{ form.DELETE }}
          </div>
          {% endfor %}

Leave a comment