如何在FormForm的子类中排除已声明的字段? [英] How can I exclude a declared field in ModelForm in form's subclass?

查看:156
本文介绍了如何在FormForm的子类中排除已声明的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我试图从 ModelForm 形式导出(子类)一个新表单,我想删除一些字段(或只有一些字段,更正确)。当然明显的方法是(基本形式来自 django.contrib.auth.forms ):

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

但是这不起作用,因为它添加/保留一个用户名字段。该字段在 UserChangeForm 中明确声明。即使将用户名添加到中也不包含属性。



解决方案

尝试这样:

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ** kwargs)
self.fields.pop('username')

class Meta(UserChangeForm.Meta):
fields =('first_name','last_name','电子邮件')

这个动态删除表单创建时的字段。


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?

解决方案

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.

这篇关于如何在FormForm的子类中排除已声明的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆