0

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

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

例如:

模型.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']

...


表格.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)"),
    )
...

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

任何想法?

谢谢。

4

1 回答 1

1

ModelForm 可以具有模型绑定和未绑定的字段。您还可以覆盖模型字段的标签属性,而无需重新定义表单中的字段:

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)"),
    )

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

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']
于 2013-08-01T05:11:30.783 回答