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

问题描述 投票:0回答:1

我将这些详细信息保存在存储在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()方法来加密密码?

django python-3.x encryption hash
1个回答
1
投票

尝试一下:

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

...
if form.is_valid():
    user = form.save(commit=False) # <---
    user.set_password(form.cleaned_data.get('password'))  # <---
    user.save()    
... 
© www.soinside.com 2019 - 2024. All rights reserved.