Rendering tabular rows with formset in django-crispy-forms
Asked Answered
L

2

7

I want to display a list of instances as a formset with django-crispy-forms and bootstrap where each instance appears as a row with all of the fields arranged horizontally.

All of the examples I can find seem to render the instances with their fields laid out vertically.

I thought using:

helper.form_class = 'form-horizontal'

might work, but that seems to have no effect.

Livingstone answered 13/2, 2014 at 12:57 Comment(0)
Q
9

This is the post that got me to a solution, and I'm providing a fuller explanation here for those just getting started with crispy forms

Forms:

from crispy_forms.helper import FormHelper, Layout
...

class MyForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ['field1', 'field2', 'field3']


MyFormSet = modelformset_factory(MyModel, form=MyForm, extra=0)


class MyFormSetHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(MyFormSetHelper, self).__init__(*args, **kwargs)
        self.layout = Layout(
            'field1',
            'field2',
            'field3'
        )
        self.template = 'bootstrap/table_inline_formset.html'

Views:

formset = MyFormSet(queryset=my_qs)
helper = MyFormSetHelper()
context = {'formset': formset, 'helper': helper}
return render(request, 'my_template.html', context)

Template:

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block content %}

<form action="" method="post">
{% csrf_token %}
{% crispy formset helper %}
</form>

{% endblock content %}
Quarter answered 21/2, 2018 at 16:38 Comment(1)
Was going crazy just to realize I had the wrong formset factory helper. Good answer!Spongin
L
4

Use the template attribute on the helper (documented here): helper.template = 'bootstrap/table_inline_formset.html'

Libau answered 4/9, 2014 at 2:5 Comment(1)
use helper.template = 'bootstrap4/table_inline_formset.html' if you are using bootstrap4.Epispastic

© 2022 - 2024 — McMap. All rights reserved.