/login 处的 TypeError 字符串必须在散列之前进行编码

TypeError at /login Strings must be encoded before hashing

我遇到这个 Django 项目的错误。我已经尝试了我能遇到的所有建议,但仍然无法正常工作。 以下是来自网络的错误。

环境:

Request Method: POST
Request URL: http://127.0.0.1:8000/login

Django Version: 2.2
Python Version: 3.9.7

    Installed Applications:
    ['main',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'django_filters']
    Installed Middleware:
    ['django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']

回溯:

File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\exception.py" in inner

    34. response = get_response(request)

File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.`response = wrapped_callback(request, *callback_args, **callback_kwargs)` 

File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\FacialRecognitionForPolice-master\main\views.py" in login
  171.`hashed = bcrypt.hashpw(request.POST['login_password'], bcrypt.gensalt())`

File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\bcrypt\__init__.py" in hashpw
  79.`raise TypeError("Strings must be encoded before hashing")`

Exception Type: TypeError at /login
Exception Value: Strings must be encoded before hashing

正如错误消息明确指出的那样,您必须先对密码进行编码。

在第 171 行的 main/views.py 中,您有

hashed = bcrypt.hashpw(request.POST['login_password'], bcrypt.gensalt())

您的 request.POST 数据是一个字符串,因此您应该将其编码为字节:

hashed = bcrypt.hashpw(request.POST['login_password'].encode(), bcrypt.gensalt())

你可以select其他编码(不是默认utf8)和.encode('ascii')(选择一个,以后不要更改,utf8可能是最好的选择一般而言)。