How do I exclude an inherited field in a form in Django?
I have the following form and inherited 开发者_C百科form:
class UsuarioAdminForm(ModelForm):
first_name = forms.CharField(label='Nombre', help_text = 'Nombre del usuario', required=True)
last_name = forms.CharField(label='Apellidos', help_text = 'Apellidos del usuario', required=True)
dni = ESIdentityCardNumberField(help_text = 'DNI del usuario', required=True, widget = forms.TextInput(attrs = {'size': 9}))
username = forms.CharField(label='Login', help_text = 'Requerido. 30 caracteres o menos. Letras, números y @/./+/-/_', widget = forms.TextInput(attrs = {'size': 15}))
#password = forms.CharField(widget=forms.PasswordInput(attrs = {'size': 12}), label='Contraseña', help_text = 'Contraseña del usuario')
email = forms.EmailField(help_text = 'Correo electrónico del usuario', required=True)
movil = ESPhoneNumberField(help_text = 'Movil principal del usuario', required=True, widget = forms.TextInput(attrs = {'size': 9 }))
is_staff = forms.BooleanField(label = "Administrador", help_text = 'Marque la casilla si desea crear un administrador')
tipo_u = forms.ChoiceField(label = 'Tipo de usuario', choices = TipoUsuarios)
def clean(self):
try:
cleaned_data = self.cleaned_data
movil = self.cleaned_data['movil']
dni = self.cleaned_data['dni']
email = self.cleaned_data['email']
except:
raise forms.ValidationError(u'Todos los campos del Formulario son Obligatorios.')
return cleaned_data
class Meta:
model = Usuario
exclude = ('is_active','date_joined', 'last_login', 'user_permissions', 'tipo', 'groups', 'is_superuser', )
class UsuarioForm(UsuarioAdminForm):
is_staff = None
def __init__(self, *args, **kwargs):
self.is_staff = None
super(UsuarioForm,self).__init__(*args, **kwargs)
class Meta:
model = Usuario
exclude = ('is_staff', 'is_active','date_joined', 'last_login', 'user_permissions', 'tipo', 'groups', 'is_superuser', 'password', )
But when I create a UsuarioForm object, why does it show the is_staff field?
Update:
If i put self.fields['is_staff'] = None
i obtain the next error:
TemplateSyntaxError at /sms/usuarios/add/user/
Caught AttributeError while rendering: 'NoneType' object has no attribute 'label'
Maybe you could change the order of this lines:
def __init__(self, *args, **kwargs):
super(UsuarioForm,self).__init__(*args, **kwargs)
self.is_staff = None
You could also do:
def __init__(self, *args, **kwargs):
super(UsuarioForm,self).__init__(*args, **kwargs)
self.fields.pop('is_staff')
This is an old question, but starting in Django 1.7.x you can just do the following:
class UsuarioForm(UsuarioAdminForm):
is_staff = None
class Meta:
model = Usuario
exclude = ('is_active', 'date_joined', 'last_login', 'user_permissions', 'tipo', 'groups', 'is_superuser', 'password')
The exclude
portion of Meta
is only for excluding ModelForm
elements, but any form element can be excluded by setting it to None
in the declarations.
From the Django docs on subclassing forms:
It’s possible to declaratively remove a Field inherited from a parent class by setting the name of the field to None on the subclass. For example:
>>> from django import forms >>> class ParentForm(forms.Form): ... name = forms.CharField() ... age = forms.IntegerField() >>> class ChildForm(ParentForm): ... name = None >>> ChildForm().fields.keys() ... ['age']
EDIT:
I think the above works in the example given, but it doesn't seem to work for fields that are created due to the Meta
on the ModelForm
. I think in those cases you need to inherit from the parent's Meta
and change the fields given.
Django form instances store the fields in the 'fields' attribute on the form itself, so in your init, after calling super, you need something like the following:
self.fields['is_staff'] = None
That should solve your problems; setting self.is_staff is just an unrelated variable (the is_staff you set on the class is a class variable not an instance variable).
精彩评论