简体   繁体   中英

Override defaults attributes of a Django form

In my Django app I have several different forms, which are similar in style. To not repeat myself over and over again, I try to rewrite the default form settings.

As a start I wanted to set some default settings for every form I use in my app and tried to subclass the django.forms.Form :

class DefaultForm(forms.Form):
    error_css_class = 'alert'
    error_class = DivErrorList
    required_css_class = 'required'
    label_suffix = ':'
    auto_id = True

class TechnicalSurveyForm(DefaultForm):
    location = forms.CharField(label='GPS Location')
    satellite = forms.ModelChoiceField(queryset=get_satellites(), empty_label=None)
    modem_sn = forms.CharField()

In my views.py I would call the Form simply with

tsurvey = TechnicalSurveyForm()

Unfortunately, the settings I set in DefaultForm are not in place (when I use TechnicalSurvey(auto_id = True, error_class = DivErrorList) they are). So, I guess my approach is totally wrong in some way. Can someone please help me out?

I guess the __init__ of forms.Form initializes attributes of a Form. You need to override the __init__ method and change attributes after Django has done its stuff.

EDIT: Indeed, after checking the django source code, you can see that attributes of a form object are initialized in the __init__ function. The method is visible on the github of django .

class DefaultForm(forms.Form):
    def __init__(self, *args, **kwargs): 
        super(forms.Form, self ).__init__(*args, **kwargs)
        self.error_css_class = 'alert'
        self.error_class = DivErrorList
        self.required_css_class = 'required'
        self.label_suffix = ':'
        self.auto_id = True

For Python beginners

This behavior is totally normal. Every attributes with the same name declared at the class declaration (as in the author example) will be override if it's also defined in the init function. There's a slightly difference between these two types of attributes declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM