【问题标题】:Unable to hash password in Django Backend无法在 Django 后端散列密码
【发布时间】:2019-06-18 20:29:34
【问题描述】:

我创建了一个自定义用户模型,因为我需要用户使用电子邮件而不是用户名登录。如果用户在前端注册,密码被散列就好了,但是当我尝试从 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

请寻求帮助。

【问题讨论】:

  • 把这个:user = super(RegisterForm, self).save(commit=False)改成这个:user = super().save(commit=False)
  • @Ahtisham 谢谢,但这不起作用
  • 你得到什么错误?
  • @Ahtisham 没有错误,但仍将密码保存为纯文本

标签: python django hash passwords


【解决方案1】:

也许您应该使用官方函数创建用户,请参见 create_user 。 https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user

【讨论】:

  • 我创建了一个自定义用户模型,因为我需要用户使用电子邮件而不是用户名登录。我用这个信息更新了我的帖子
【解决方案2】:

在 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

【讨论】:

  • 你的代码改成这个了吗?在您编辑的问题中,您仍然有 user = super(RegisterForm, self).save(commit=False) 这一行
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2019-07-17
  • 1970-01-01
相关资源
最近更新 更多