Nick P.
Nick P.

Reputation: 275

Dynamically remove an exclusion on a field in a django model form

I'd like to programmatically enable a field that is excluded by default...

model:

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    an_excluded_field = models.TextField()
    my_bool = models.BooleanField(default=False) # this is the field to conditionally enable...

form:

class MyModelForm(ModelForm):
    class Meta:
        model = EmailTemplate
        excludes = ('an_excluded_field', 'my_bool')

I would like to do something like this(or something to that effect...):

form = MyModelForm(enable_my_bool=True)

This is almost like this post(i want the field excluded by default): How can I exclude a declared field in ModelForm in form's subclass?

Upvotes: 4

Views: 3780

Answers (2)

davegaeddert
davegaeddert

Reputation: 3339

If you overwrite the constructor then you need to pop the value from kwargs before calling the superclass constructor (like mgalgs) mentions:

def __init__(self, *args, **kwargs):
    enable_my_bool = kwargs.pop('enable_my_bool', True) # True is the default
    super(MyModelForm, self).__init__(*args, **kwargs)
    if not enable_my_bool:
        self.fields.pop('my_bool')

Upvotes: 0

Dolan Antenucci
Dolan Antenucci

Reputation: 15942

1) You could define a second version of the form:

class MyExcludedModelForm(MyModelForm):
    class Meta:
        excludes = ('my_bool',) # or could use fields in similar manner

2) You could overwrite the form's constructor:
(same as described in the other SO post you reference)

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        if not kwargs.get('enable_my_bool', false):
            self.fields.pop('my_bool')
        super(MyModelForm, self).__init__(*args, **kwargs) # maybe move up two lines? (see SO comments)

Upvotes: 6

Related Questions