我正在开发一个项目,我有一个用户输入用户名电子邮件和passowrd的表单。我想哈希密码并保存。我注意到,当我通过管理页面创建用户时,它会自动创建密码并在保存之前对其进行哈希处理。我想做同样的事情。我有什么方法可以做到这一点......
这就是我现在对视图的看法......
def signup(request):
# the following will determine if the form is submitted or not
if request.method == 'POST':
form = SignupForm(request.POST)
# the following section validates the entire form and processed the data
if form.is_valid():
# the following will make sure the data is clean and then store them
# into new variables
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
# the folloiwng will make sure the password and verification are matching
# before storing the info into the database
if password == verify:
new_user = User.objects.create(
username = username,
password = password,
email = email,
)
# the following will store the username of the account that was just
# created in to the session so that the app can track the user that
# is logged in
request.session['username'] = username
return redirect('profile_setup')
else:
# if password and verification dont match, a message will be sent
# back to the user so they can fill in the correct info.
message = 'Password and Verify dont match'
parameters = {
'form':form,
'message':message,
}
return render(request, 'tabs/signup.html', parameters)
else:
# this will display the form if it waas not submmited.
form = SignupForm()
message = 'Fill out the form'
parameters = {
'form':form,
'message':message,
}
return render(request, 'tabs/signup.html', parameters)
答案 0 :(得分:2)
请参阅django官方文档set_password
if password == verify:
new_user = User.objects.create(
username = username,
email = email,
)
new_user.set_password(password)
new_user.save()
答案 1 :(得分:1)
from django.contrib.auth.hashers import make_password
if password == verify:
new_user = User.objects.create(
username = username,
password = make_password(password),
email = email,
)
希望这就是你要找的东西