带有布局帮助器的自定义ModelForm在每次刷新时都会在布局传递后重新添加按钮Div

时间:2019-11-06 13:53:57

标签: python django django-crispy-forms

为了保持ModelForm的干燥状态,我创建了一个带有ModelForm的自定义FormHelper,因此可以在Div后面附加一个Submit和一个{ {1}的{1}}按钮。它还提供了添加自定义布局的可能性。

当我未指定自定义布局时,此方法就很好用,但是当我这样做时,每次刷新页面时,它都会附加按钮Cancel(在没有自定义布局时不会发生)< / p>

这是自定义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

这是我没有刷新页面3次后没有custom_layout的表单: form with no custom_layout

这是我刷新页面3次后带有custom_layout的表单: enter image description here

我知道我可以使用ModelForm方法来避免此问题,但是那样我将无法将按钮居中。

如果有人能帮助我解决这个重新提出的问题,我将不胜感激。 预先感谢。

1 个答案:

答案 0 :(得分:0)

几乎在精神崩溃后,我终于想通了。

对于试图实现相同目标的任何人,这是解决方案(由于只使用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)

就是这样。现在,您可以使自定义Layout更加干燥。希望您能找到有用的信息。

相关问题