3

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?

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
neurotroph
  • 43
  • 6
  • Using Django 1.7, it looks like the above *does* work (at least the required_css_class does). – SaeX Oct 20 '14 at 10:25

1 Answers1

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.

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97