【问题标题】:Django - Save a Excel file to a model's FileFildDjango - 将 Excel 文件保存到模型的 FileFild
【发布时间】:2020-12-28 14:56:22
【问题描述】:

我想在我的 excel_file 字段中保存一个文件,但我有这个错误:
'utf-8' 编解码器无法解码位置 15 中的字节 0x9d:无效起始字节


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)




【问题讨论】:

    标签: python django django-models


    【解决方案1】:

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

    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 parameter [Django-doc]会防止保存excel文件导致再次调用模型的save方法,从而导致无限递归。


    注意:请不要使用 blanket except:尝试将异常处理限制为 具体例外。其他异常不应被捕获,而应由 调用子程序的代码流。通过使用except,你基本上 将停止任何异常,但这通常不是一个好主意,因为调用者 因此假定调用成功。

    【讨论】:

    • 谢谢,但现在我有另一个错误:超过最大递归深度 致命的 Python 错误:无法从堆栈溢出中恢复。这创建了一个包含许多文件的文件夹,而不是一个带有 new_test.xlsx 名称的新 Excel 文件
    • @alpha: 是的,那是因为self.excel_file.save 当然会触发Modelsave
    • @alpha: 和open(...) 将创建文件的副本,因为稍后您可能打算更新文件,因此它们应该彼此独立。
    • @alpha:你可以省略递归:self.excel_file.save(name, File(myFile), save=False)
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    相关资源
    最近更新 更多