带有 FormHelper 的自定义 ModelForm 在每次刷新布局后重新附加按钮 Div

Custom ModelForm with FormHelper re-appends buttons Div after each refresh when a layout is passed

为了保持我的 ModelForm 干燥,我创建了一个带有 FormHelper 的自定义 ModelForm,因此我可以将 Div 附加到 SubmitCancel 按钮到 layout。它还提供了添加自定义布局的可能性。

当我没有指定自定义布局时,这工作得很好,但是当我这样做时,每次刷新页面时它都会附加按钮 Div(当没有自定义布局时不会发生这种情况)

这是习俗ModelForm:

class ModelFormWithHelper(ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        kwargs = self.get_helper_kwargs()
        helper_class = FormHelper(self)
        if 'custom_layout' in kwargs:
            self.helper.layout = kwargs['custom_layout']
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-12'
        self.helper.field_class = 'col-md-12'
        self.helper.layout.append(
            Div(
                HTML('<br>'),
                FormActions(
                    Submit('submit', 'Save'),
                    HTML('<a class="btn btn-secondary" href="{{ request.META.HTTP_REFERRER }}">Cancel</a>')
                ),
                css_class='row justify-content-center',
            ),
        )

    def get_helper_kwargs(self):
        kwargs = {}
        for attr, value in self.Meta.__dict__.items():
            if attr.startswith('helper_'):
                new_attr = attr.split('_', 1)[1]
                kwargs[new_attr] = value
        return kwargs

这是 ModelForm:

class CargoForm(ModelFormWithHelper):
    class Meta:
        model = Cargo
        exclude = []
        helper_custom_layout = Layout(
            Div(
                'name',
                'order',
                css_class='col-6 offset-3',
            ),
        )

这是我刷新页面3次后没有custom_layout的表格:

这是我刷新页面 3 次后带有 custom_layout 的表格:

我知道我可以使用 self.helper.add_input 方法来避免这个问题,但那样我就无法将按钮居中。

如果有人能帮我解决这个重新附加的问题,我将不胜感激。 提前致谢。

差点精神崩溃,终于想通了

对于任何试图实现相同目标的人,这里是解决方案(我摆脱了 get_helper_kwargs 方法,因为我只使用 helper_custom_layout

# Put it in a variable to avoid repeating it twice
buttons_layout = Layout(
    Div(
        HTML('<br>'),
        FormActions(
            Submit('submit', 'Save'),
            HTML('<a class="btn btn-secondary" href="{{ request.META.HTTP_REFERER }}">Cancel</a>')
        ),
        css_class='row justify-content-center',
    ),
)


class ModelFormWithHelper(ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        custom_layout = getattr(self.Meta, 'helper_custom_layout', None)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-md-12'
        self.helper.field_class = 'col-md-12'
        if custom_layout:
            self.helper.layout = Layout(custom_layout, buttons_layout)
        else:
            self.helper.layout.append(buttons_layout)

就是这样。现在你可以让你的自定义 Layouts 更干一点了。希望你能发现这很有用。