繁体   English   中英

无法在Django后端中哈希密码

[英]Unable to hash password in Django Backend

我创建了一个自定义用户模型,因为我需要用户使用电子邮件而不是用户名登录。 如果用户在前端注册,则密码会被很好地散列,但是当我尝试从Django的后端创建密码时,密码将另存为纯文本。

admin.py

def save(self, commit=True):
    # Save the provided password in hashed format
    user = super(RegisterForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password"])
    if commit:
        user.save()
    return user

forms.py

class RegisterForm(forms.ModelForm):
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email',)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("email is taken")
        return email

    def clean_password2(self):
        # Check that the two password entries match
        password = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")
        if password and password2 and password != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password'])
        # user.is_applicant = True
        user.is_active = True  
        if commit:
            user.save()
        return user

请寻求帮助。

在admin.py的“用户创建”表单中,将def save编辑为此,

def save(self, commit=True):
    user = super().save(commit=False)
    user.set_password(self.cleaned_data['password'])

    if commit:
        user.save()
    return user

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM