Reputation: 61
I got an error,TypeError: Unicode-objects must be encoded before hashing. I wrote codes,
user = Data()
passwd = request.data['password']
md5 = hashlib.md5()
md5.update(passwd)
user.password = md5.hexdigest()
print(user.password)
user.save()
Traceback says
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/opt/project/app/views.py", line 27, in create
md5.update(passwd)
I added #coding:utf-8 to top of the code,but same error happens.What is wrong in my codes?How should I fix this?
Upvotes: 1
Views: 1176
Reputation: 599460
The error tells you what you need to do: encode the password to a bytestring.
md5.update(passwd.encode('utf-8'))
Note though you probably shouldn't be doing this at all; if you want to use a user's password, use the set_password()
method of the User model.
(And please don't randomly add encoding declarations to your script; that only effects literal characters in the file.)
Upvotes: 3