Django crispy-forms:带有 TextArea 字段的 2 列表单

Django crispy-forms: 2 column form with a TextArea field

我正在尝试使用 crispy-forms Layouts 创建一个美观的 2 列表单。当其中 1 个字段是 TextArea 字段时,它会变得混乱。 (当我没有 TextArea 字段时一切正常)

此代码:

## forms.py
class BasicForm(forms.Form):
   label_1 = forms.CharField(label='label1')
   label_2 = forms.CharField(label='label2')
   label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(
                Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'),
            ),

            Row(
                Field('label_2', wrapper_class='col-md-6', css_class='row-fluid'),
                Field('label_3', wrapper_class='col-md-6')
            )
        )

产生这种格式:

还有这段代码:

       self.helper.layout = Layout(
        Row(
            Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'),
            Field('label_3', wrapper_class='col-md-6')
        ),

        Row(
            Field('label_2', wrapper_class='col-md-6', css_class='row-fluid')
        )
    )

产生这种格式:

我想分开 2 列,每 1 列应该堆叠到顶部,仅相对于它本身。

编辑

(添加我想要的最终结果草图)

类似于:

并说我有更多的领域:

看起来您只需要稍微改变一下布局 - 那些 Row 对象充当清除元素,所以这就是为什么您的 label_2 字段显示在 下方 label_3 文本区域的基线 - 因为它已被清除。

因此解决方案是使用 Div class 创建 2 列,然后将 wrapper_class 属性放在您的字段上。您还可以删除 Field 对象,只使用字段名称(因为您不需要指定任何属性):

## forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Row, Div, Layout

class BasicForm(forms.Form):
   label_1 = forms.CharField(label='label1')
   # label_2 uses a widget with custom attribute(s)
   label_2 = forms.CharField(label='label2', widget=forms.TextInput(attrs={'readonly': 'readonly'}))
   label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea)
   def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(
                Div('label_1', 'label_2',
                    css_class='col-md-6'
                ),
                Div(
                    'label_3',
                    css_class='col-md-6'
                ),
            ),
        )