使'Enter'键默认为Django脆皮形式的某个按钮?

Make 'Enter' key default to a certain button in a Django crispy form?

我有一个从 django-two-factor-auth-library 继承 PhoneNumberForm 的表单。它呈现一个文本框,可在其中输入 phone 数字,并在其下方呈现一个“后退”按钮和“下一步”按钮。问题在于,当填写完表单并且用户按下键盘上的 'Enter' 键时,会触发后退按钮。

我试过交换这两个按钮,这给了我想要的行为,但不是正确的布局。但我确实看到在 FormActions 中首先定义的按钮在按下 Enter 时被选中。

我也尝试过向我的“下一步”按钮添加一个 'autofocus' 字段,但它只在页面加载时聚焦在按钮上,而不是在我将焦点切换到文本框并输入数字之后.

我想保持当前的顺序(左侧为“后退”按钮,右侧为“下一步”),但让 Enter 键触发“下一步”按钮。我该怎么做?

from crispy_forms.helper import FormHelper
from crispy_forms import layout as crispy
from crispy_forms import bootstrap as twbscrispy


def __init__(self, **kwargs):
    super(PhoneNumberForm, self).__init__(**kwargs)
    self.helper = FormHelper()
    self.helper.form_class = 'form form-horizontal'
    self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2'
    self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
    self.helper.layout = crispy.Layout(
        crispy.Fieldset(
            '',
            'number'
        ),
        twbscrispy.FormActions(


            twbscrispy.StrictButton(
                _('Back'),
                css_class='btn-default',
                type='submit',
                value='method',
                name='wizard_goto_step',
            ),



            twbscrispy.StrictButton(
                _('Next'),
                css_class='btn-primary',
                type='submit',
            )



        )
    )

您的浏览器正在使用 作为表单中 type = "submit" 的第一个按钮。

如果您将 "Back" 按钮 type 更改为“button”,那么您的 "Next" 按钮将成为表单中的第一个提交按钮, 将激活它。

如果您使用 "onclick" 属性并为表单提供 "id" 属性,您仍然可以使用 "Back" 按钮来提交表单。

例如

# ...
self.helper = FormHelper()
self.helper.form_id = 'wizard_form_id'
# ...
twbscrispy.StrictButton(
    _('Back'),
    css_class='btn-default',
    type='button',
    value='method',
    name='wizard_goto_step',
    onclick="document.getElementById('wizard_form_id').submit();",
),
twbscrispy.StrictButton(
    _('Next'),
    css_class='btn-primary',
    type='submit',
)