Override defaults attributes of a Django form

丶灬走出姿态 提交于 2019-12-19 09:44:16

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18020227/override-defaults-attributes-of-a-django-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!