我通读了django-storages docs,建议您使用以下内容将文件保存到云存储(在我的情况下为GCS):
>>> obj2 = Resume()
>>> obj2.pdf.save('django_test.txt', ContentFile('more content'))
>>> obj2.pdf
<FieldFile: tests/django_test_.txt>
>>> obj2.pdf.size
但是,按照相同的逻辑,我正在努力使用FileField对象将Pandas DataFrame保存为CSV:
我的代码:
df = load_some_df()
print(df.head())
# prints contents of df
contents = ContentFile(df.to_csv(index=False, header=True))
output_file_name = 'df.csv'
instance = MyModel()
instance.output_file.save(output_file_name, contents)
上面的错误给了我
('`data` must be bytes, received', <class 'str'>)
答案 0 :(得分:0)
将df.to_csv(index=False, header=True)
替换为df.to_csv(index=False, header=True).encode('utf-8')