set_password()方法未在自定义Django用户模型中加密密码

时间:2019-11-14 09:17:59

标签: django python-3.x encryption hash

我将这些详细信息保存在存储在MySQL中的自定义用户模型中,但是密码没有得到加密;它以纯文本格式保存。

def regauth(request):    
    if request.method == "POST":
        form = UserAuth(data=request.POST)
        # user_form = UserAuth(data=request.POST)
        if form.is_valid():
            try:
                messages.info(request, 'inside try')
                user = form.save()
                user.set_password(form.password)
                user.save()    
                return redirect('login_url')
            except:
                messages.info(request, 'inside exception')
                return render(request, 'registration/registration.html', {'form': form})    
    else:
        user_form = UserAuth()
    return render(request, 'registration/registration.html', {'form': user_form})
  

Forms.py

class UserAuth(forms.ModelForm):
  password = forms.CharField(widget=forms.PasswordInput())
  class Meta:
      model = RegAuth
      fields = "__all__"

如何确保正确调用set_password()方法来加密密码?

1 个答案:

答案 0 :(得分:1)

尝试一下:

使用commit = False保存会为您提供一个模型对象,然后您可以添加额外的数据并将其保存。

...
if form.is_valid():
    user = form.save(commit=False) # <---
    user.set_password(form.cleaned_data.get('password'))  # <---
    user.save()    
...