How can I exclude a declared field in ModelForm in form's subclass?
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.a开发者_如何转开发uth.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.
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.
精彩评论