python - Django 表单 - 设置标签

标签 python django inheritance django-forms

我有一个继承自其他 2 个表单的表单。在我的表单中,我想更改在其中一个父表单中定义的字段的标签。有谁知道如何做到这一点?

我正在尝试在我的 __init__ 中执行此操作,但它会引发错误,提示“'RegistrationFormTOS' 对象没有属性 'email'”。有谁知道我该怎么做?

谢谢。

这是我的表单代码:

from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationFormUniqueEmail
from registration.forms import RegistrationFormTermsOfService

attrs_dict = { 'class': 'required' }

class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
    """
    Subclass of ``RegistrationForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.

    """
    email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address'))

    def __init__(self, *args, **kwargs):
        self.email.label = "New Email Label"
        super(RegistrationFormTOS, self).__init__(*args, **kwargs)

    def clean_email2(self):
        """
        Verifiy that the values entered into the two email fields
        match. 
        """
        if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
            if self.cleaned_data['email'] != self.cleaned_data['email2']:
                raise forms.ValidationError(_(u'You must type the same email each time'))
        return self.cleaned_data

最佳答案

你应该使用:

def __init__(self, *args, **kwargs):
    super(RegistrationFormTOS, self).__init__(*args, **kwargs)
    self.fields['email'].label = "New Email Label"

注意首先你应该使用 super 调用。

关于python - Django 表单 - 设置标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636905/

相关文章:

python - Django python - 类属性值是否在请求之间共享?

java - 继承避免重复的成员变量

C++ 类继承和运算符重载;运算符重载会被继承吗?

Python 复制函数行为

python - 当它不是 Django 模型时,是否可以在数据库中使用表?

python - 如何在 Visual Studio 代码中避免这种烦人的自动完成

python - 使用 django-crispy 组合布局时出错

c++ - 使用 protected 和继承时无法访问在类中声明的私有(private)成员

Python matplotlib 动画重复

python - 需要从列表中删除 None