为了保持我的ModelForm
干燥,我创建了一个带有ModelForm
的自定义FormHelper
,因此我可以将带有Div
和Submit
按钮的Cancel
附加到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)
就是这样。现在,您可以使自定义Layout
稍微干燥一些。希望您能找到有用的信息。