Django没有将文件保存到FileField。 IOError:文件未打开以供阅读

时间:2017-03-16 16:55:46

标签: django django-file-upload

我有这个Django代码,我无法将文件保存到模型FileField

    # create stocklist object and populate it
    stocklist = StockList.objects.create(retailer=retailer)
    with open("retailer_stocklist.csv", "wb") as csv_file:
        for row in table_data:
            writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
            writer.writerow([row["EAN"], row["NAME"], row["QUANTITY"],
                             row["UNIT"], row["SKU"], row["PRICE"]])

        stocklist.csv_file.save("retailer_stocklist.csv", File(csv_file))

该模型如下所示:

class StockList(models.Model):
    csv_file = models.FileField(null=True, blank=True)

我收到错误:

  

IOError:文件未打开以供阅读

1 个答案:

答案 0 :(得分:2)

将文件模式从wb更改为r + b