I have the following django scheme:
forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
class ContactForm(forms.Form):
name_param = forms.CharField()
email_param = forms.EmailField()
message_param = forms.CharField(widget=forms.Textarea)
captcha_div = "<div class=\"g-recaptcha\" data-sitekey=\"xxxxxoBjAnlYtR\"></div> <br>"
class Meta:
pass
def __init__(self, *args, **kwargs):
"""
Forms for contact.
"""
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'id-contactForm'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
self.helper.form_method = 'post'
self.fields['name_param'].label = "Name"
self.fields['email_param'].label = "Email"
self.fields['message_param'].label = "Message"
self.helper.layout = Layout(
Field('name_param'),
Field('email_param'),
Field('message_param'),
HTML(self.captcha_div),
)
self.helper.add_input(Submit('submit', 'Submit'))
My question is
So that even if I resize the browser they will stick on the top of their respective fields.
答案 0 :(得分:2)
用于呈现表单的HTML和CSS可以由template pack和layout定义。默认情况下,当您不指定任何内容时,crispy-forms使用引导程序模板包和默认布局。从我所看到的,您正在使用具有默认布局的bootstrap3模板包。在这种情况下,您可以使用attributes of the FormHelper对显示进行一些基本的更改。
事实上,这是您在设置这些属性时所做的事情:
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
根据这两条说明,您说所有标签都应包含CSS类col-lg-2
,所有字段的格式应为col-lg-8
。这就是为什么标签位于字段的左侧并分别采用视图的1/6 th 和4/6 th (如果使用12列网格)。
由于您希望标签和字段位于不同的行上,因此您只需提供一个采用整个视图宽度的CSS类:
self.helper.label_class = 'col-lg-12'
self.helper.field_class = 'col-lg-12'
请注意,如果您需要响应式内容,则可以利用引导网格的强大功能。例如,如果您希望与大屏幕上的标签位于同一行上的字段,以及小屏幕上的标签下方,则可以执行以下操作:
self.helper.label_class = 'col-md-4'
self.helper.field_class = 'col-md-8'
你甚至可以给这个领域提供几个CSS类。