python - Django - 将 Excel 文件保存到模型的 FileFild
问题描述
我想在我的 excel_file 字段中保存一个文件,但我有这个错误:
'utf-8' codec can't decode byte 0x9d in position 15: invalid start byte
class Product(models.Model):
excel_file = models.FileField(upload_to='upload', blank=True)
def save(self, *args, **kwargs):
try :
myFile = open('excel_file.xlsx', 'r')
name = "new_test.xlsx"
self.excel_file.save(name, File(myFile))
super().save(*args, **kwargs)
except Exception as e:
print(e)
解决方案
您没有以二进制模式打开文件,因此出现错误:
class Product(models.Model):
excel_file = models.FileField(upload_to='upload', blank=True)
def save(self, *args, **kwargs):
try :
# binary mode ↓
with open('excel_file.xlsx', 'rb') as myFile:
name = 'new_test.xlsx'
self.excel_file.save(name, File(myFile), save=False)
super().save(*args, **kwargs)
except Exception as e:
print(e)
这里的save=False
参数[Django-doc]会防止保存excel文件导致save
再次调用模型的方法,从而导致无限递归。
注意:请不要使用毯子,除了:尝试将异常处理限制为特定异常。其他异常不应被捕获,而是由调用子例程的代码流处理。通过使用
except
,您基本上将停止任何异常,但这通常不是一个好主意,因为调用者因此假定调用成功。
推荐阅读
- c++ - 如何使用谷歌测试用例测试迭代器值?
- sql-server - SSMS 中数据库名称后的 (Synchronized) 是什么意思。
- android - PC usb主机通过libusb与Android配件模式通信
- javascript - 在 create-react-app 中修改 antd 主题而不弹出 webpack
- visual-studio - 一个Output类型的类库的项目不能直接启动asp.net mvc
- html - 将样式应用于“display:flex”内部
- python - ModelForm form_valid() 函数的成功/重定向 URL 问题
- clojure - Clojure 无法读取输入的 csv 文件
- python - 用于数据分析类的 Python 装饰器
- excel - 如何在 Excel 中为公式添加条件