Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying multiple Rows and Columns in django-crispy-forms

I'm using django-crispy-forms with Twitter Bootstrap , and I'm having some issues with customizing my forms into multiple rows and columns. One example problem is that nothing happens when I try to split the form into two columns:

class SomeForm(ModelForm):

    helper = FormHelper()
    helper.layout = Layout(
        Column('field1', 'field3'),
        Column('field2', 'field4'),
        )
    )

    class Meta:
        model = Model

Looking at the html output, I see that there is the <div class="formColumn">, but the form is displayed in one single column. Maybe is this an css issue? I am using Bootstrap 2.1.

like image 696
martinpaulucci Avatar asked Aug 27 '12 14:08

martinpaulucci


2 Answers

Thanks maraujo.

I've achieved this using the div tag and the bootstrap docs: http://twitter.github.com/bootstrap/scaffolding.html

class SomeForm(ModelForm):

    helper = FormHelper()
    helper.layout = Layout(
        Div(
            Div('field1', css_class='span6'),
            Div('field3', css_class='span6'),  
        css_class='row-fluid'), 
    )

    class Meta:
        model = Model

For bootstrap3 replace span6 with col-xs-6 http://getbootstrap.com/css/#grid

like image 83
martinpaulucci Avatar answered Sep 30 '22 16:09

martinpaulucci


Small 2018 update on the answer by martinpaulucci:

For Bootstrap 4 and latest django-crispy-forms 1.7.2 use:

class SomeForm(ModelForm):

    helper = FormHelper()
    helper.layout = Layout(
        Div(
            Field('field1', wrapper_class='col-md-3'),
            Field('field3', wrapper_class='col-md-9'),  
        css_class='form-row') 
    )

    class Meta:
        model = Model

The use of the Field tag in stead of the Div tag avoids another unnecessary wrapper div. To improve on that you can replace crispy-forms Row with your own if you're going to use more than one row:

class Row(Div):
    css_class = "form-row"

then use:

class SomeForm(ModelForm):

    helper = FormHelper()
    helper.layout = Layout(
        Row(
            Field('field1', wrapper_class='col-md-3'),
            Field('field3', wrapper_class='col-md-9')  
        ) 
    )

    class Meta:
        model = Model
like image 20
Pepijn Avatar answered Sep 30 '22 18:09

Pepijn