[Django]-Override defaults attributes of a Django form

6👍

✅

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.

Leave a comment