簡體   English   中英

為什么UserCreationForm在Django的模型類中定義了UserName字段明確?

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

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

我注意到的是以下內容:

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

為什么需要在fields明確提及此(“用戶名”)。因為有一個username UserCreationForm段再次定義UserCreationForm 為什么? 為什么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

fields屬性存在,因為沒有它,該模型中的所有字段都將顯示在表單上(ModelForm的默認行為是在沒有“fields”或“exclude”屬性的情況下顯示模型中的所有字段) 。

password字段不在其中,因為表單上顯示的密碼字段實際上不是存儲在模型中的密碼字段 - 模型中的密碼字段是散列密碼,而表單上顯示的密碼字段是普通文本字段。 因此,處理此表單的代碼會獲取這些文本密碼,確保它們是相同的,然后創建“真實”密碼並將其存儲在模型中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM