[Django] Layout for Crispy Form: Multiple Fields in One Line

How to use Crispy Forms and Bootstrap to make a form like this:

  1. Add title label (.label) and detail description (.help_text) for form field.
  2. Layout multiple fields in one line/row (horizontally inline): Use FormHelper() and Layout()

With crispy forms, you can set the layout within a subclassed forms.ModelForm, without writing anything in template.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Div, Button, Fieldset
from .models import CustomUser

class CustomUserForm(forms.ModelForm):
class Meta:
model = CustomUser
# specify what fields should be used in this form.
fields = ('email',
'last_name', 'first_name',
'phone_number',
'mobile_number',
'zip_code', 'home_address',
'bank_id_first', 'bank_id_last')

def __init__(self, *args, submit_title="儲存編輯", **kwargs):
super().__init__(*args, **kwargs)
my_field_text= [
# (field_name, Field title label, Detailed field description)
('email', '郵件', '電子郵件將會作為您往後登入時使用'),
('last_name', '姓', ''),
('first_name', '名', ''),
('phone_number', '電話', '郵寄一律採用掛號,所以手機與住家電話請至少要有一支確定能找得到人'),
('mobile_number', '手機', ''),
('zip_code', '郵遞區號', ''),
('home_address', '地址', ''),
('bank_id_first', '銀行代碼', ''),
('bank_id_last', '銀行帳號', '此帳號為對賬與退貨退款時使用,不會用於其它用途'),
]
for x in my_field_text:
self.fields[x[0]].label=x[1]
self.fields[x[0]].help_text=x[2]
# Set layout for fields.
self.helper = FormHelper()
self.helper.layout = Layout(
Div('email', 'password'),
Div(
Div('last_name', css_class="col-sm-2"),
Div('first_name', css_class="col-sm-10"),
css_class = 'row'
),
Div('phone_number', 'mobile_number'),
Div(
Div('zip_code', css_class="col-sm-2"),
Div('home_address', css_class="col-sm-10"),
css_class = 'row'
),
Div(
Div('bank_id_first', css_class="col-sm-2"),
Div('bank_id_last', css_class="col-sm-10"),
css_class = 'row'
),
)
self.helper.add_input(Submit('submit', submit_title))