如何排除表单子类中 ModelForm 中声明的字段?
在 Django 中,我试图从 ModelForm 表单派生(子类)一个新表单,我想在其中删除一些字段(或者只包含一些字段,更正确)。当然,显而易见的方法是(基本表单来自 django.contrib.auth.forms ):
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
fields = ('first_name', 'last_name', 'email')
但这不起作用,因为它还添加/保留了一个用户名字段在结果形式中。该字段已在 UserChangeForm
中显式声明。即使将用户名
添加到排除
属性也没有帮助。
有什么适当的方法可以排除它并且我错过了一些东西吗?这是一个错误吗?有一些解决方法吗?
In Django, I am trying to derive (subclass) a new form from ModelForm
form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.forms
):
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
fields = ('first_name', 'last_name', 'email')
But this does not work as it adds/keeps also an username
field in the resulting form. This field was declared explicitly in UserChangeForm
. Even adding username
to exclude
attribute does not help.
Is there some proper way to exclude it and I am missing something? Is this a bug? Is there some workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
这会在创建表单时动态地从表单中删除字段。
Try this:
This dynamically removes a field from the form when it is created.
看来(通用)解决方法(仍然缺少将
exclude
纳入考虑范围)是:但这对我来说就像一个错误。
It seems the (generic) workaround (still missing taking
exclude
into the account) is:But this smells like a bug to me.