【问题标题】:why is the UserCreationForm has UserName field explicity defined in model class in Django?为什么 UserCreationForm 在 Django 的模型类中明确定义了 UserName 字段?
【发布时间】:2014-04-27 23:19:16
【问题描述】:

我正在查看source code 中的UserCreationForm django.contrib.auth.forms

我注意到以下几点:

class Meta:
            model = User
            fields = ("username",)

为什么需要在fields 中明确提及这个(“用户名”)。因为UserCreationForm 再次定义了一个username 字段。为什么?为什么Password fields没有包含在上述Meta class定义中?

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }
    username = forms.RegexField(label=_("Username"), max_length=30,
        regex=r'^[\w.@+-]+$',
        help_text=_("Required. 30 characters or fewer. Letters, digits and "
                      "@/./+/-/_ only."),
        error_messages={
            'invalid': _("This value may contain only letters, numbers and "
                         "@/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ("username",)

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

【问题讨论】:

    标签: django django-forms django-users django-models


    【解决方案1】:

    fields 属性之所以存在,是因为如果没有它,该模型中的所有字段都会显示在表单上(ModelForm 的默认行为是显示模型中的 所有 字段,在缺少“字段”或“排除”属性)。

    password 字段不在其中,因为表单上显示的密码字段并不是模型中存储的真正密码字段——模型中的密码是散列密码,而显示在表单是普通的文本字段。因此,处理此表单的代码获取这些文本密码,确保它们相同,然后创建“真实”密码并将其存储在模型中。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2018-06-11
      • 2020-10-25
      • 2014-11-11
      • 2020-05-05
      • 2013-05-09
      • 2022-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多