简体   繁体   English

覆盖Django表单的默认属性

[英]Override defaults attributes of a Django form

In my Django app I have several different forms, which are similar in style. 在我的Django应用程序中,我有几种不同的形式,它们的风格相似。 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 : 首先,我想为我在我的应用程序中使用的每个表单设置一些默认设置,并尝试将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 在我的views.py中,我会简单地使用表单

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). 不幸的是,我在DefaultForm中设置的设置不到位(当我使用TechnicalSurvey(auto_id = True, error_class = DivErrorList)时)。 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. 我想forms.Form__init__初始化Form的属性。 You need to override the __init__ method and change attributes after Django has done its stuff. 在Django完成其工作之后,您需要覆盖__init__方法并更改属性。

EDIT: Indeed, after checking the django source code, you can see that attributes of a form object are initialized in the __init__ function. 编辑:的确,在检查django源代码后,您可以看到表单对象的属性在__init__函数中初始化。 The method is visible on the github of django . 该方法在django的github上可见

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 对于Python初学者

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. 如果在init函数中也定义了在类声明中声明的每个具有相同名称的属性(如在作者示例中),则将覆盖它们。 There's a slightly difference between these two types of attributes declaration. 这两种类型的属性声明之间略有不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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