Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
alexandernst Avatar asked May 29 '18 15:05

alexandernst


1 Answers

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...)
like image 78
neverwalkaloner Avatar answered Nov 07 '22 23:11

neverwalkaloner