a bytes-like object is required, not 'str'

TypeError at /admin/goods/goodssku/add/

a bytes-like object is required, not 'str'
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/goods/goodssku/add/
Django Version: 1.8.2
Exception Type: TypeError
Exception Value:
a bytes-like object is required, not 'str'
Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/files/storage.py in save, line 67
Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3
Python Version: 3.5.1
Python Path:
['/Users/mac/PycharmProjects/dailyfresh/apps',
 '/Users/mac/PycharmProjects/dailyfresh',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-10.0.1-py3.5.egg',
 '/Users/mac/PycharmProjects/dailyfresh',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_display',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
 '/Users/mac/Library/Python/3.5/lib/python/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend',
 '/Users/mac/PycharmProjects/dailyfresh']
Server time: 星期四, 7 一月 2021 16:54:20 +0800

原因是_save()方法返回的是str类型而并非是byte类型

修改之前:

def _save(self,name,content):
'''保存文件时使用'''
# name:你选择上传文件的名字 test.jpg
# content:包含你上传文件内容的File对象
# 创建一个Fdfs_client对象
client = Fdfs_client(self.client_conf)

# 上传文件到fast dfs系统中
res = client.upload_by_buffer(content.read())

# dict
# {
# 'Group name': group_name,
# 'Remote file_id': remote_file_id,
# 'Status': 'Upload successed.',
# 'Local file name': '',
# 'Uploaded size': upload_size,
# 'Storage IP': storage_ip
# }
if res.get('Status') != 'Upload successed.':
# 上传失败
raise Exception('上传文件到fast dfs失败')

# 获取返回的文件ID
filename = res.get('Remote file_id')
print(type(filename))
return filename
修改之后:
def _save(self,name,content):
'''保存文件时使用'''
# name:你选择上传文件的名字 test.jpg
# content:包含你上传文件内容的File对象
# 创建一个Fdfs_client对象
client = Fdfs_client(self.client_conf)

# 上传文件到fast dfs系统中
res = client.upload_by_buffer(content.read())

# dict
# {
# 'Group name': group_name,
# 'Remote file_id': remote_file_id,
# 'Status': 'Upload successed.',
# 'Local file name': '',
# 'Uploaded size': upload_size,
# 'Storage IP': storage_ip
# }
if res.get('Status') != 'Upload successed.':
# 上传失败
raise Exception('上传文件到fast dfs失败')

# 获取返回的文件ID
filename = res.get('Remote file_id')
print(type(filename))
return filename.decode()
原文地址:https://www.cnblogs.com/xpptt/p/14247434.html