14

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?

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • Just to clarify: not working means the field keeps apearing in the form even if the line `self._meta.exclude = ("active",)` gets executed? Or are you getting errors? – Ralf May 29 '18 at 15:35
  • And is it just a typo or is `RandomForm` really calling the super method from `ServiceForm` ? – Ralf May 29 '18 at 15:36
  • @Ralf Indeed. "Doesn't work" means that the field keeps showing. Also, yes, that's a typo. – alexandernst May 29 '18 at 15:49

2 Answers2

13

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...)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • That will override the verbose_name, default value and so on in my model. – alexandernst May 29 '18 at 15:48
  • @alexandernst I didn't have chance to test it, but try `if not self.instance: self.fields.pop('active')`. You should add `active` to meta's fields also. – neverwalkaloner May 29 '18 at 15:55
  • 1
    With Django 3.2, `if not self.instance` is false even for new instances. Changing the condition to `if not self.instance.id` will achieve the expected behavior. – kyuden Jan 16 '23 at 12:58
-5

Django ModelForm provides exclude attribute. Have you tried that?

class RandomForm(ModelForm):

    class Meta:
        model = models.Service
        exclude = ['is_active']
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36
  • 1
    didn't dv but I think the OP means with "dynamically" that depending on some properties (for example whether the instance already exists), the form should render differently, so we can *reuse* the *same* form, but it will display different fields. – Willem Van Onsem May 29 '18 at 15:41