April 18, 2025

Csv From Django

in blog Django on Fundor333
original entry Csv From Django

Some time you need to export a file into a specific format for some use like upload to the old system. In this case I need to have a CSV file which another software fill.

I wrote a ClassView for this case, this class.

class CsvCarsDownload(View):
 def get(self, request, *args, **kwargs):
 response = HttpResponse(content_type="text/csv")
 response["Content-Disposition"] = 'attachment; filename="cars.csv"'
 my_dict = [{
 "brand": "Ford",
 "model": "Mustang",
 "year": 1964
 }]
 writer = csv.DictWriter(
 response, dialect="excel", fieldnames=my_dict[0].keys()
 )
 writer.writeheader()
 for element in my_dict:
 writer.writerow(element)
 return response

You can change the type of the the CSV changing the dialect with one of the type of the CSV dialect (excel, excel_tab, unix_dialect) and changing the my_dict with any type of list of dict.