re: Django inline formsets with Class-based views and crispy forms VIEW POST

FULL DISCUSSION
 

Hey Xenia,

thank you for this helpful post. That's exactly what I was looking for. I've applied a small modification to make your solution a bit more crispy ;-)

Instead of putting all the form layout stuff into the file formset.html it would a better solution to add a LayoutHelper to the CollectionTitleForm:

forms.py

from django import forms
from .models import Collection, CollectionTitle
from django.forms.models import inlineformset_factory
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Fieldset, Div, Row, HTML, ButtonHolder, Submit
from .custom_layout_object import Formset

import re


class CollectionTitleForm(forms.ModelForm):

    class Meta:
        model = CollectionTitle
        exclude = ()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        formtag_prefix = re.sub('-[0-9]+$', '', kwargs.get('prefix', ''))

        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Row(
                Field('name'),
                Field('language'),
                Field('DELETE'),
                css_class='formset_row-{}'.format(formtag_prefix)
            )
        )


CollectionTitleFormSet = inlineformset_factory(
    Collection, CollectionTitle, form=CollectionTitleForm,
    fields=['name', 'language'], extra=1, can_delete=True
)


class CollectionForm(forms.ModelForm):

    class Meta:
        model = Collection
        exclude = ['created_by', ]

    def __init__(self, *args, **kwargs):
        super(CollectionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = True
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-3 create-label'
        self.helper.field_class = 'col-md-9'
        self.helper.layout = Layout(
            Div(
                Field('subject'),
                Field('owner'),
                Fieldset('Add titles',
                         Formset('titles')),
                Field('note'),
                HTML("<br>"),
                ButtonHolder(Submit('submit', 'Save')),
            )
        )

Then you can simplify your formset.html

{% load crispy_forms_tags %}
{% load staticfiles %}

<style type="text/css">
  .delete-row {
    align-self: center;
  }
</style>

{{ formset.management_form|crispy }}

{% for form in formset.forms %}
  {% for hidden in form.hidden_fields %}
    {{ hidden|as_crispy_field }}
  {% endfor %}
  {% crispy form %}
{% endfor %}

<br>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'mycollections/libraries/django-dynamic-formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
    $('.formset_row-{{ formset.prefix }}').formset({
        addText: 'add another',
        deleteText: 'remove',
        prefix: '{{ formset.prefix }}',
    });
</script>

The advantage is that the layout is now modified by crispy_forms applying the selected template pack (e.g. bootstrap4). Only the CSS .delete-row must be secified to center the remove button of the django-formset plugin because only a link is added if the containing element is not a HTML-table.

Best regards,
andi

 

Thanks for your contribution! I merged it into a new branch :)

code of conduct - report abuse