Search code examples
djangodjango-file-upload

Django not saving file to FileField. IOError: File not open for reading


I have this Django code, I can't save the file to the models 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))

The model looks like this:

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

I get the error:

IOError: File not open for reading


Solution

  • change the file mode from wb to r+b