django-crispy-forms: Align button with fields vertically

1.7k views Asked by At

I've been struggling to get my form (including the button) in just one line using django-crispy-forms.

I eventually found a solution, but I decided posting the question together with the answer, in case somebody else faces the same problem.

Code in forms.py was as follows:

class SearchForm(forms.Form):
    [...]

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-inline'

        self.helper.layout = Layout(
                    Field('From', placeholder='From'),
                    Field('To', placeholder='To'),
                    Field('Date', placeholder='Date'),
                    ButtonHolder(Submit('submit', 'Search', css_class='btn btn-primary'))
        )

But the button was appearing in a second line.

button appears in a second line

I tried as alternative

self.helper.form_class = 'form-horizontal'

but no difference.

1

There are 1 answers

0
J0ANMM On BEST ANSWER

I found a solution based on this post in github.

That is to adapt the Layout by using a FormActions object:

self.helper.layout = Layout(
            Field('From', placeholder='From'),
            Field('To', placeholder='To'),
            Field('Date', placeholder='Date'),
            FormActions(ButtonHolder(Submit('submit', 'Search', css_class='btn btn-primary')))
        )

And all fields and the button are perfectly aligned:

desired result, all fields and button in one line