2017-08-08 31 views
-1

我正在一个项目,我有一个用户输入用户名电子邮件和密码的窗体。我想散列密码并保存。我注意到当我通过管理页面创建用户时,它会自动创建密码并在保存之前对其进行哈希处理。我想做同样的事情。有没有什么办法,我这样做...不能弄清楚如何哈希passowrd django

这就是我现在所拥有的对视......

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) 

回答

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, 
       ) 

希望这是你在找什么

2

请参阅django官方文档set_password

if password == verify: 
    new_user = User.objects.create(
     username = username, 
     email = email, 
    ) 
    new_user.set_password(password) 
    new_user.save()