Django-Storages ('`data` must be bytes, received', <class 'str'>) when saving a model field

Viewed 489

I read through the django-storages docs which suggest using the following to save files to cloud storage (GCS in my case):

>>> obj2 = Resume()
>>> obj2.pdf.save('django_test.txt', ContentFile('more content'))
>>> obj2.pdf
<FieldFile: tests/django_test_.txt>
>>> obj2.pdf.size

However, following the same logic, I'm struggling to save a Pandas DataFrame as a CSV using FileField object:

My code:

   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)

The above gives me the error:

('`data` must be bytes, received', <class 'str'>)
1 Answers

Replace df.to_csv(index=False, header=True) with df.to_csv(index=False, header=True).encode('utf-8')

Related