在Django中,能否在ModelForm的子子类中排除字段?
我有一个“通用”的 InternForm
,它是从 ModelForm
继承来的,里面定义了一些常用的消息、控件等等。
我还定义了一个叫 ApplyInternForm
的子类,这个申请表是所有人都可以访问的,但我想隐藏一些“高级”字段。
我该如何在这个表单的子类中覆盖 exclude
设置呢?
class InternForm(ModelForm):
# ...
class Meta:
model = Intern
exclude = ()
class ApplyInternForm(InternForm):
def __init__(self, *args, **kwargs):
super(ApplyInternForm, self).__init__(*args, **kwargs)
self.Meta.exclude = ('is_active',) # this doesn't work
3 个回答
-1
你可以把小部件设置为隐藏:
class ApplyInternForm(InternForm):
class Meta:
widgets = {
'is_active': forms.HiddenInput(required=False),
}
1
这样做不行。当你创建一个表单的子类时,你想要排除的字段已经存在了。不过,你可以在你的 __init__()
方法里调用 super()
之后,从 self.fields
中把它们删掉。
3
在子类中定义一个 Meta
类对我来说是有效的:
class InternForm(ModelForm):
# ...
class Meta:
model = Intern
class ApplyInternForm(InternForm):
class Meta:
model = Intern
exclude = ('is_active',)