Johannes Pertl
Johannes Pertl

Reputation: 983

How can I extend a Django Form class?

I want to create multiple, similar forms based on this one:

class DatabaseForm(forms.Form):
    
    label = "Database label"  # This does not work, but I also can't define it in __init__ method, as I can't access self below in "name" field

    name = forms.BooleanField(label=label, required=False)
    username = forms.CharField(label="Username", required=False)
    password = forms.CharField(label="Password", required=False)

where I only change the label, like this:

class MySQLForm(DatabaseForm):
    label = "MySQL"  # Somehow override label of super class

How can I achieve this?

Upvotes: 2

Views: 395

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can set the field label in __init__ and access the class attribute via self.label

class DatabaseForm(forms.Form):

    label = "Database label"

    name = forms.BooleanField(required=False)
    username = forms.CharField(label="Username", required=False)
    password = forms.CharField(label="Password", required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].label = self.label


class MySQLForm(DatabaseForm):
    label = "MySQL"

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476554

You can override the label in the __init__ constructor:

class MySQLForm(DatabaseForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].label = 'MySQL'

You can also use a parameter in the DatabaseForm:

class DatabaseForm(forms.Form):
    name_label = 'Database label'
    name = forms.BooleanField(label=None, required=False)
    username = forms.CharField(label='Username', required=False)
    password = forms.CharField(label='Password', required=False)
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].label = self.name_label

class MySQLForm(DatabaseForm):
    name_label = 'MySQL'

Upvotes: 2

Related Questions