如何排除表单子类中 ModelForm 中声明的字段?

发布于 2024-09-10 13:36:29 字数 448 浏览 2 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绅士风度i 2024-09-17 13:36:29

试试这个:

class MyUserChangeForm(UserChangeForm):

  def __init__(self, *args, **kwargs):
    super(MyUserChangeForm, self).__init__(*args, **kwargs)
    self.fields.pop('username')

  class Meta(UserChangeForm.Meta):
    fields = ('first_name', 'last_name', 'email')

这会在创建表单时动态地从表单中删除字段。

Try this:

class MyUserChangeForm(UserChangeForm):

  def __init__(self, *args, **kwargs):
    super(MyUserChangeForm, self).__init__(*args, **kwargs)
    self.fields.pop('username')

  class Meta(UserChangeForm.Meta):
    fields = ('first_name', 'last_name', 'email')

This dynamically removes a field from the form when it is created.

迷路的信 2024-09-17 13:36:29

看来(通用)解决方法(仍然缺少将 exclude 纳入考虑范围)是:

def __init__(self, *args, **kwargs):
  super(UserChangeForm, self).__init__(*args, **kwargs)
  for field in list(self.fields):
    if field not in self._meta.fields:
      del self.fields[field]

但这对我来说就像一个错误。

It seems the (generic) workaround (still missing taking exclude into the account) is:

def __init__(self, *args, **kwargs):
  super(UserChangeForm, self).__init__(*args, **kwargs)
  for field in list(self.fields):
    if field not in self._meta.fields:
      del self.fields[field]

But this smells like a bug to me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文