I have a django Formset that I'd like to layout in the middle of another form. I'm using django-crispy-forms to set the layout in the parent form's __init__
:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field, Div
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Div(
Div(Field('foo'), css_class='span3'),
Div(Field('bar'), css_class='span4'),
css_class='row'
),
Field('baz', css_class='span1'),
...
)
self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary offset4'))
My template simply renders the form using the {% crispy %}
tag.
I'd like to know how I should incorporate the formset. Should I instantiate it in the above init function? How do I refer to it there?
There are other examples of form and formset combos online that have one render after the other serially, but I'm wondering whether I can have more control over how they fit together with crispy's layout.
Basing on above solution Formset(LayoutObject), you would combine django-dynamic-formset & crispy. On my order page I have:
Now it is simple and clear, ModelForms are:
Formset helper layout:
Add/delete inlines, saving order with formset operations work as expected.
I solved this without modifying Crispy Forms, by creating a new field type that renders a formset:
It needs a template to render the formset, which gives you control over exactly how it's rendered:
You can use it to embed a formset in your layouts just like any other Crispy layout element:
This is currently not supported in crispy-forms. Your only option would be to use
|as_crispy_field
filter (not documented yet, sorry).I have started development of this feature for
{% crispy %}
tag and in a feature branch, it's all explained here: https://github.com/maraujop/django-crispy-forms/issues/144I'm looking for feedback, so if you are still interested, feel free to post.
A slight modification to the earlier answer by qris.
This update (as suggested by Alejandro) will allow for our custom Formset Layout Object to use a FormHelper object to control how the formset's fields are rendered.
Template (used to render formset):
Now it can be used in any layout just like any other crispy forms layout object.