vdboor
vdboor

Reputation: 22526

Django ModelForms, override a field, keep the same label

In my ModelForm, I have to override some settings of the fields (e.g. choices, or required state). This requires declaring the entire field again as formfield.

Is there a simple way to access the verbose_name of the model field, so this doesn't have to redefined?

Upvotes: 1

Views: 1556

Answers (1)

Mark Lavin
Mark Lavin

Reputation: 25164

You don't have to redefine the field to change these settings. You can access the field in the form __init__ like below.

class MyForm(forms.ModelForm):

    class Meta(object):
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_field'].required = True

Upvotes: 9

Related Questions