alexandernst
alexandernst

Reputation: 15099

Dynamically excluding field from Django ModelForm

I want to exclude, programatically, a field in my form. Currently I have this:

class RandomForm(BaseForm):
    def __init__(self, *args, **kwargs):

        # This doesn't work
        if kwargs["instance"] is None:
            self._meta.exclude = ("active",)

        super(ServiceForm, self).__init__(*args, **kwargs)

        # This doesn't work either
        if kwargs["instance"] is None:
            self._meta.exclude = ("active",)

    class Meta:
        model = models.Service
        fields = (...some fields...)

How can I exclude the active field only when a new model is being created?

Upvotes: 14

Views: 4133

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47374

You can solve it this way:

class RandomForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(RandomForm, self).__init__(*args, **kwargs)
        if not self.instance:
            self.fields.pop('active')

    class Meta:
        model = models.Service
        fields = (...some fields...)

Upvotes: 13

Sijan Bhandari
Sijan Bhandari

Reputation: 3061

Django ModelForm provides exclude attribute. Have you tried that?

class RandomForm(ModelForm):

    class Meta:
        model = models.Service
        exclude = ['is_active']

Upvotes: -5

Related Questions