以 Django 形式保存散列版本的用户密码不起作用 [英] Saving Hashed Version of User Password in Django Form Not Working

查看:20
本文介绍了以 Django 形式保存散列版本的用户密码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试保存用户密码的散列版本,但没有成功.

I have been trying to save the hashed version of a user password but it's not working.

forms.py:

class up_form(forms.ModelForm):
    class Meta:
        model = Users
        fields =['email', 'password', 'username', 'status']

views.py:

from myapp.forms import up_form
from django.contrib.auth.hashers import make_password
def register(request):
    if request.method == 'POST':
        sign_up = up_form(request.POST or None)
        if sign_up.is_valid():
            sign_up.password = make_password(sign_up.cleaned_data['password'])
            sign_up = sign_up.save(commit = False)
            sign_up.status = 1
            sign_up.save()

但我的 password 仍然以纯文本格式保存.我该如何解决这个问题?

But my password still get saved in plain text. How do I come around this?

推荐答案

您需要切换语句的顺序,因为您已将对象命名为与表单本身相同的名称.

You need to switch the order of your statements, because you have named the object as the same name as the form itself.

if request.method == 'POST':
    sign_up = up_form(request.POST)
    if sign_up.is_valid():
        sign_up = sign_up.save(commit = False)
        sign_up.password = make_password(sign_up.cleaned_data['password'])

我希望您也从该方法返回响应,并在 POST 请求后适当地重定向用户.

I hope you are also returning a response from the method, and redirecting users appropriately after the POST request.

考虑这个版本:

def register(request):
    form = up_form(request.POST or None)
    if form.is_valid():
        sign_up = form.save(commit=False)
        sign_up.password = make_password(form.cleaned_data['password'])
        sign_up.status = 1
        sign_up.save()
        return redirect('/thank-you/')
    return render(request, 'sign_up_form.html', {'form': form})

这篇关于以 Django 形式保存散列版本的用户密码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆