不在“models.py”和“forms.py”之间重复代码的方法?

时间:2013-08-01 02:34:21

标签: django

我正在编写自定义用户模型字段。

当我这样做的时候,我意识到我在复制“models.py”和“forms.py”之间的代码?

例如:

models.py

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
        db_index=True,
    )

    full_name = forms.CharField(
        max_length=64,
    )
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

...


forms.py

class RegistrationForm(forms.Form):
    error_css_class = 'error'
    required_css_class = 'required' 

    email = forms.EmailField(
        label=_("Email"),
    )
    full_name = forms.CharField(
        label=_("Full Name"),
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput,
        label=_("Password"),
    )
    password2 = forms.CharField(
        widget=forms.PasswordInput,
        label=_("Password (again)"),
    )
...

在这里,我发现自己定义了两次字段,但我不知道是否有必要,如果不是,那么我如何将这两个字段合并为一行:(

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

ModelForm可以包含模型绑定和未绑定的字段。您还可以覆盖模型字段的label属性,而无需在表单中重新定义字段:

class RegistrationForm(forms.ModelForm):
    class Meta:
        model = MyUser

    error_css_class = 'error'
    required_css_class = 'required' 

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['full_name'].label = _("Full Name")

    password2 = forms.CharField(
        widget=forms.PasswordInput,
        label=_("Password (again)"),
    )

虽然,我看不到您在表单中为任何模型字段提供不同标签的位置。您也可以随时在模型级别添加label属性:

class MyUser(AbstractBaseUser):
    email = models.EmailField(u'Email Address', max_length=255, unique=True,
        db_index=True)
    full_name = forms.CharField(u'Full Name', max_length=64)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']