Search code examples
djangopandasdataframedjango-modelsfilefield

How to save a dataframe as csv file in filefield


I am trying to save a dataframe as a csv file in a model object's filefield but it is not saving it correctly, the file that is getting saved, contains some other language characters!! please tell what I am doing wrong??

new_df = df.to_csv(columns=['A', 'B'], index=False)
doc.csvfile.save(f'{doc.id}.csv', ContentFile(new_df))

Solution

  • Hello you can try to save csv file with below code

    import csv
    from io import StringIO
    from django.core.files.base import ContentFile
    
    new_df = df.to_csv(columns=['A', 'B'], index=False)
    
    csv_buffer = StringIO()
    csv_writer = csv.writer(csv_buffer)
    csv_writer.writerow(new_df)
    
    csv_file = ContentFile(csv_buffer.getvalue().encode('utf-8'))
    doc.csvfile.save('output.csv', csv_file)