python - 覆盖 Django 表单的默认属性

标签 python django django-forms

在我的 Django 应用程序中,我有几种不同的形式,它们的风格相似。为了不一遍又一遍地重复自己,我尝试重写默认表单设置。

作为开始,我想为我在我的应用程序中使用的每个表单设置一些默认设置,并尝试子类化 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()

在我的 views.py 中,我会简单地调用表单

tsurvey = TechnicalSurveyForm()

不幸的是,我在 DefaultForm 中设置的设置没有到位(当我使用 TechnicalSurvey(auto_id = True, error_class = DivErrorList) 时它们是)。所以,我想我的方法在某种程度上是完全错误的。有人可以帮帮我吗?

最佳答案

我猜 forms.Form__init__ 初始化了 Form 的属性。在 Django 完成它的工作后,您需要覆盖 __init__ 方法并更改属性。

编辑: 确实,在查看django 源代码后,您可以看到表单对象的属性是在__init__ 函数中初始化的。 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

Python 初学者

这种行为是完全正常的。如果在 init 函数中也定义了在类声明中声明的每个具有相同名称的属性(如在作者示例中),则将被覆盖。有一个 slightly difference在这两种类型的属性声明之间。

关于python - 覆盖 Django 表单的默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020227/

相关文章:

python - 我目前正在为我的类(class)解决普朗克黑体函数的问题

python - 如何修复 Django 中的错误 "invalid literal for int() with base 10: ' Independence'?

Django 数据库错误 : relation "django_site"

python - 在验证和保存表单之前,如何从 ImageField 打开图像?

javascript - 当按下 Flutter 中的按钮时,是否可以从 .js 或 .py 文件运行 js 或 python 脚本? (不是 Flutter Web)

python - 如何使用 GitPython 指定 Commit 的 committed_date?

python - 神交学习- "How many words"

python - Elastic Beanstalk 中的 enum34 问题

django - 我如何在管理员之外复制 admin.TabularInline(在用户端?)

python - 我的表单的 is_valid 方法返回 false