Dan Abramov
Dan Abramov

Reputation: 268255

In Django, can I exclude a field in ModelForm sub-subclass?

I have a “generic” InternForm that inherits from ModelForm and defines common messages, widgets, etc.

I defined a subclass called ApplyInternForm for application form that is accessible to everyone and I want to hide some of the “advanced” fields.

How can I override exclude setting in the form's subclass?

class InternForm(ModelForm):

    # ...

    class Meta:
        model = Intern
        exclude = ()

class ApplyInternForm(InternForm):
    def __init__(self, *args, **kwargs):
        super(ApplyInternForm, self).__init__(*args, **kwargs)
        self.Meta.exclude = ('is_active',)  # this doesn't work

Upvotes: 1

Views: 1377

Answers (3)

ArturM
ArturM

Reputation: 703

You can change widget to hidden:

class ApplyInternForm(InternForm):
    class Meta:
        widgets = {
            'is_active': forms.HiddenInput(required=False),
        }

Upvotes: -1

Dan Abramov
Dan Abramov

Reputation: 268255

Defining a Meta class in the subclass worked for me:

class InternForm(ModelForm):

    # ...

    class Meta:
        model = Intern

class ApplyInternForm(InternForm):

    class Meta:
        model = Intern
        exclude = ('is_active',)

Upvotes: 3

patrys
patrys

Reputation: 2769

Not in this way, no. When you subclass a form the fields you want to exclude are already there. You can however remove them from self.fields after calling super() in your __init__().

Upvotes: 1

Related Questions