Dynamically excluding field from Django ModelForm
Asked Answered
R

2

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?

Rinarinaldi answered 29/5, 2018 at 15:22 Comment(3)
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?Maestoso
And is it just a typo or is RandomForm really calling the super method from ServiceForm ?Maestoso
@Maestoso Indeed. "Doesn't work" means that the field keeps showing. Also, yes, that's a typo.Rinarinaldi
M
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...)
Manama answered 29/5, 2018 at 15:28 Comment(3)
That will override the verbose_name, default value and so on in my model.Rinarinaldi
@Rinarinaldi 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.Manama
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.Oscillator
U
-5

Django ModelForm provides exclude attribute. Have you tried that?

class RandomForm(ModelForm):

    class Meta:
        model = models.Service
        exclude = ['is_active']
Unplug answered 29/5, 2018 at 15:31 Comment(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.Aldoaldol

© 2022 - 2024 — McMap. All rights reserved.