在 Django 中,我可以排除 ModelForm 子类中的字段吗?
我有一个“通用”InternForm
,它继承自 ModelForm
并定义通用消息、小部件等。
我为应用程序表单定义了一个名为 ApplyInternForm
的子类每个人都可以访问它,我想隐藏一些“高级”字段。
如何覆盖表单子类中的排除
设置?
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
I have a “generic” InternForm
that inherits from ModelForm
and defines common messages, widgets, etc.
I defined a subclass called ApplyInternForm
for application form that is accessible to everyone and I want to hide some of the “advanced” fields.
How can I override exclude
setting in the form's subclass?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在子类中定义一个
Meta
类对我有用:Defining a
Meta
class in the subclass worked for me:不是这样的,不。当您对表单进行子类化时,您想要排除的字段已经存在。不过,您可以在
__init__()
中调用super()
后从self.fields
中删除它们。Not in this way, no. When you subclass a form the fields you want to exclude are already there. You can however remove them from
self.fields
after callingsuper()
in your__init__()
.您可以将小部件更改为隐藏:
You can change widget to hidden: