Dynamically remove an exception on a field in the form of a django model

I would like to programmatically include 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...

the form:

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

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

form = MyModelForm(enable_my_bool=True)

It's almost like this post (I want the field to be excluded by default): How can I exclude the declared field in ModelForm in a subclass of the form?

+3
source share
2 answers

1) You can define the second version of the form:

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

2) You can overwrite the form constructor:
(same as described in another SO post that you are referencing)

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)
+5
source

, pop kwargs (, mgalgs):

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')
0

Source: https://habr.com/ru/post/1795309/


All Articles