首页 > 解决方案 > 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)




标签: pythondjangodjango-models

解决方案


您没有以二进制模式打开文件,因此出现错误:

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,您基本上将停止任何异常,但这通常不是一个好主意,因为调用者因此假定调用成功。


推荐阅读