简体   繁体   English

为什么UserCreationForm在Django的模型类中定义了UserName字段明确?

[英]why is the UserCreationForm has UserName field explicity defined in model class in Django?

I am looking at source code for UserCreationForm in django.contrib.auth.forms 我在django.contrib.auth.forms查看UserCreationForm source code

what I notice is that the following: 我注意到的是以下内容:

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

why is there a need to explicitly mention this ("username",) in the fields .because there is a username field defined again the UserCreationForm . 为什么需要在fields明确提及此(“用户名”)。因为有一个username UserCreationForm段再次定义UserCreationForm why is it? 为什么? and why Password fields are not included in the above Meta class definition? 为什么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

The fields attribute is there because, without it, all fields from that model would show on the form (the default behavior of a ModelForm is to show all fields from the model, in the absence of a "fields" or "exclude" attribute). fields属性存在,因为没有它,该模型中的所有字段都将显示在表单上(ModelForm的默认行为是在没有“fields”或“exclude”属性的情况下显示模型中的所有字段) 。

The password field isn't in it because the password fields shown on the form aren't really the password field stored in the model--the one in the model is the hashed password, whereas the ones shown on the form are normal text fields. password字段不在其中,因为表单上显示的密码字段实际上不是存储在模型中的密码字段 - 模型中的密码字段是散列密码,而表单上显示的密码字段是普通文本字段。 So the code that processes this form takes those text passwords, makes sure they're the same, and then creates the "real" password and stores that in the model. 因此,处理此表单的代码会获取这些文本密码,确保它们是相同的,然后创建“真实”密码并将其存储在模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UserCreationForm没有字段用户名 - UserCreationForm has no field username Django UserCreationForm错误:ModelForm没有指定模型类 - Django UserCreationForm Error: ModelForm has no model class specified 如何从Django中的UserCreationForm中删除用户名字段 - How to remove the Username field from the UserCreationForm in Django 在 Django 的 UserCreationForm 中添加“日期字段”并将其连接到 model - Add "Date field" in UserCreationForm in Django and connect it to model 如何在Django的UserCreationForm / User Model中将客户的电子邮件作为用户名? - How to make customer's email as the username in UserCreationForm / User Model in Django? 'UserCreationForm'对象没有属性'get_username'django 1.8 - 'UserCreationForm' object has no attribute 'get_username' django 1.8 如何从 Django 的 UserCreationForm 中的用户名字段禁用自动对焦? - How to disable autofocus from username field in Django's UserCreationForm? Django 检查是 Model 字段是否定义了选择 - Django Check is a Model Field has chocies defined or not 如何扩展 django UserCreationForm model 以包含电话号码字段 - How to extend django UserCreationForm model to include phone number field 自定义Django ForeignKey字段到定义的模型类 - Custom Django ForeignKey field to a defined model class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM