jvc26
jvc26

Reputation: 6513

How to add classes to subforms within formset in django-crispy-forms

What I'm after is the ability to style forms within my formset:

<form>
    {{ formset management stuff here }}
<div class="formset-child">
    {{ formset child form here }}
</div>
<div class="formset-child">
    {{ formset child form here }}
</div>
</form>

Is there a way to do this cleanly with the FormHelper (as for adding submit buttons etc.) or do I need to do it in my template and manually loop over the formset?

Upvotes: 2

Views: 326

Answers (1)

Aidas Bendoraitis
Aidas Bendoraitis

Reputation: 4003

You can use layout.HTML() block to render the inline forms there like this:

layout_blocks = []
layout_blocks.append(layout.Fieldset(
    _("Children"),
    layout.HTML("""{% load crispy_forms_tags i18n %}
    {{ formsets.children.management_form }}
    <div id="children">
        {% for form in formsets.children.forms %}
            <div class="child formset-form">
                {% crispy form %}
            </div>
        {% endfor %}
    </div>
    <!-- used by javascript -->
    <div id="children_empty_form" class="child formset-form" style="display: none">
        {% with formsets.children.empty_form as form %}
            {% crispy form %}
        {% endwith %}
    </div>
    """),
    css_id="children_fieldset",
))
layout_blocks.append(bootstrap.FormActions(
   PrimarySubmit('submit', _('Save')),
))
self.helper.layout = layout.Layout(*layout_blocks)

Each of your inline forms can have the helper with its own layout.

Upvotes: 1

Related Questions