的Django == 1.11.3
以下代码似乎违反了DRY原则。 但我没有创建一个mixin来概括这三个字符串:
你能帮我一把吗?
class BatchDateInputForm(forms.ModelForm):
class Meta:
model = BatchDateInput
exclude = []
widgets = {
'user': forms.HiddenInput(),
'from_date': forms.SelectDateWidget(years=get_years()),
'through_date': forms.SelectDateWidget(years=get_years()),
}
class FrameDateForm(ModelForm):
class Meta:
model = FrameDate
exclude = []
widgets = {
'frame': forms.HiddenInput(),
'from_date': forms.SelectDateWidget(years=get_years()),
'through_date': forms.SelectDateWidget(years=get_years())
}
答案 0 :(得分:2)
这实际上取决于您尝试重载的属性类型。这是一种在不使用元类的情况下实现这一目标的方法,它不是很漂亮,但会完成这项工作
class BaseMeta:
exclude = []
widgets = {
'from_date': forms.SelectDateWidget(years=get_years()),
'through_date': forms.SelectDateWidget(years=get_years())
}
class BatchDateInputForm(forms.ModelForm):
class Meta(BaseMeta):
model = BatchDateInput
widgets = BaseMeta.widgets.copy()
widgets.update({
'user': forms.HiddenInput(),
})
class FrameDateForm(ModelForm):
class Meta(BaseMeta):
model = FrameDate
widgets = BaseMeta.widgets.copy()
widgets.update({
'frame': forms.HiddenInput(),
})
注意您必须始终重新注册以复制dict
的其他BaseMeta
属性,否则它将更新所有子类的dict
属性
答案 1 :(得分:0)
未经测试,但我认为这应该可行:
def get_widgets():
return {
'user': forms.HiddenInput(),
'from_date': forms.SelectDateWidget(years=get_years()),
'through_date': forms.SelectDateWidget(years=get_years()),
}
class BatchDateInputForm(forms.ModelForm):
class Meta:
model = BatchDateInput
exclude = []
widgets = get_widgets()
class FrameDateForm(ModelForm):
class Meta:
model = FrameDate
exclude = []
widgets = get_widgets()