在 Django Crispy Forms 中将提交按钮呈现在与表单字段相同的行中

问题描述 投票:0回答:1

我正在使用 Django Crispy Forms,而不是让提交按钮呈现在其余字段下方,我想将它移动到与另一个字段相同的行。我当前的表单代码如下:

class SetForm(forms.ModelForm):
    class Meta:
        model = Set
        fields = ['exercise', 'actual_weight', 'actual_reps', 'actual_difficulty']

    helper = FormHelper()
    helper.form_method = 'POST'

    helper.layout = Layout(
        Row(
            Column('exercise', css_class='form-group col-md-12 mb-0'),
            css_class='form-row'
        ),
        Row(
            Column('actual_weight', css_class='form-group col-6 mb-0'),
            Column('actual_reps', css_class='form-group col-6 mb-0'),
        ),
        Row(
            Column('actual_difficulty', css_class='form-group col-6 mb-0'),
            Column(helper.add_input(Submit('submit', 'Submit', css_class='form-group btn-primary col-6 mb-0'))),
        )
    )

虽然这不起作用,但提交按钮仍然位于表单下方自己的行中,尽管

col-6
类似乎已应用。

我试着查看 this question,但它既没有答案也没有使用 Django Crispy Forms,以及 this one,但是那个专注于前置文本并且修改这个用例的答案并不简单。请帮忙!

python django django-forms django-templates django-crispy-forms
1个回答
0
投票

想通了:

class SetForm(forms.ModelForm):
    class Meta:
        model = Set
        fields = ['exercise', 'actual_weight', 'actual_reps', 'actual_difficulty']

    helper = FormHelper()
    helper.form_method = 'POST'

    helper.layout = Layout(
        Row(
            Column('exercise', css_class='form-group col-md-12 mb-0'),
            css_class='form-row'
        ),
        Row(
            Column('actual_weight', css_class='form-group col-6 mb-0'),
            Column('actual_reps', css_class='form-group col-6 mb-0'),
        ),
        Row(
            Column('actual_difficulty', css_class='form-group col-6 mb-0'),
            Column(Submit('submit', 'Submit', css_class='btn-primary col-6')),
        )
    )

诀窍是删除删除

helper.add_input
条款。这可以将提交按钮添加到表单,但显然它也使它把提交按钮放在表单之后,而不是使用布局嵌入。

但请注意:此解决方案并不完美:提交按钮现在与所需的“actual_difficutly”字段位于同一行,但它与 actual_difficulty 字段的高度不同。这是因为 actual_difficulty 字段有足够的高度来容纳标签和输入,而提交按钮则没有。为了让这个解决方案看起来更理想,它仍然需要一些自定义的 css 应用于提交按钮以使其具有相同的高度。

© www.soinside.com 2019 - 2024. All rights reserved.