Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exclude an inherited field in a form in Django?

I have the following form and inherited 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'

like image 864
grouser Avatar asked Mar 21 '11 13:03

grouser


People also ask

How do you exclude a specific field from a model form?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do I override a Django form?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

How do I delete a field in Django?

If you want to drop the data completely, you need to create a Django migration (using ./manage.py makemigrations preferably) that will remove those columns from the database.


2 Answers

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')
like image 73
Fábio Diniz Avatar answered Sep 18 '22 14:09

Fábio Diniz


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.

like image 27
Tim Tisdall Avatar answered Sep 19 '22 14:09

Tim Tisdall