【问题标题】:Django crispy-forms: 2 column form with a TextArea fieldDjango crispy-forms:带有 TextArea 字段的 2 列表单
【发布时间】:2019-12-31 07:28:02
【问题描述】:

我正在尝试使用 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 列应堆叠到顶部,仅相对于自身。

编辑

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

类似:

说我有更多的领域:

【问题讨论】:

  • 你能更清楚地解释一下你想要的结果是什么吗?也许你可以画一个图并附上它?我不知道您所说的“我想将 2 列分开,每列 1 应该堆叠到顶部,仅相对于自身”是什么意思。谢谢!
  • @YellowShark 谢谢哥们。我添加了我的最终结果应该看起来如何相似的草图。
  • 谢谢,太好了 - 有道理。希望我的回答能让您更接近,如果您需要更多帮助,请告诉我!

标签: django layout django-forms textarea django-crispy-forms


【解决方案1】:

看起来您只需要稍微更改布局 - 那些 Row 对象充当清除元素,这就是为什么您的 label_2 字段显示在 低于 @ 的基线987654323@ textarea - 因为它已被清除。

所以解决方案是创建 2 列,使用 Div 类,然后将 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'
                ),
            ),
        )

【讨论】:

  • 成功了,谢谢!我现在遇到了其他问题。我如何将label2(例如)设置为readonly 字段而其他字段不是?
猜你喜欢
  • 2014-12-21
  • 2021-01-08
  • 2014-02-22
  • 2022-01-04
  • 2016-12-20
  • 2020-04-06
  • 2021-05-29
  • 2012-07-03
  • 2014-12-07
相关资源
最近更新 更多