django.contrib.auth utf-8 ascii python 'Unicode-objects must be encoded before hashing'
Question: I have a Django web project that was originally authored on a Linux machine
(UTF-8) and I cloned the git repository code to my windows machine. When
accessing Django's admin interface running from the built-in development web
server, I am unable to authenticate. After running a few of the authentication
calls from the Django shell it appears there is an encoding issue. Yes, I know
the best solution would be not to use Microsoft Windows, but this is the
development environment my company has provided / decided for me.

Unfortunately, adding this to my settings file does not work on windows:

    
    
    import locale
    locale.setlocale(locale.LC_ALL, 'UTF-8') 
    

From VS 2013 PTVS version 2.2 Immediate Window C:\Python27\Lib\site-
packages\django\contrib\auth\backends.py:

    
    
    user.set_password('mark')
    None
    user.save()
    None
    user.check_password('mark')
    True
    user.check_password('mark')
    error: Unicode-objects must be encoded before hashing
    user.password
    u'bc$$2b$12$FaJjXbx.DupiSJvLJbGg7.YLDd6Ci8wS9BdASm0z94SRttMb.MFwO'
    

You can work around Unicode issue by converting password hash and the password
variable string to ASCII:

    
    
    password = password.encode('ascii')
    None
    user.check_password(password)
    True
    

Clearly this is the wrong approach and I would rather set the default encoding
to 'UTF-8' for Python running this Django project globally.

How might I best solve this?

Note: Creating new django projects locally on windows machine work just fine
because they are in default ASCII encoding. Also, sys.setdefaultencoding is no
longer an option... it would likely cause more problems anyway. I don't have
time to upgrade all our apps to Python 3.x.


Answer: It turns out the implementation of bcrypt in Django package django-
bcrypt==0.9.2, was not coded properly. I worked around issue by:

  1. I removed django_bcrypt Django app from settings.py file:
    
        INSTALLED_APPS = ( ...
    # django_bcrypt,
    ...)
    

  2. I then added this to the settings.py:
    
        FILE_CHARSET='UTF-8'
    

  3. I then simply reset my admin user's password in order to re-hash password using Django's default hash algorithm.
    
        python manage.py changepassword *username* 
    

Now I am able to authenticate on to the local development server again using
my windows workstation. I am sure there is another work around to get bcrypt
working with Django, but I only needed this to work on my workstation for
development and testing.

