Csv From Django
This post is part of the Django Tricks series
- Django Rest Framework: Multiple post
- Make a Excel Django combo
- Django With Barcode and Qrcode
- Django Return Pdf With Reportlab
- Django List View With Show More
- Message and Allert With Django and Boostrap
- Csv From Django
- Django Generate Barcode With Reportlab
- Add Minor Things to Django for templating
- Htmx Django and Django Table2
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.
The code
I wrote a ClassView for this case, this class. 1
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 responseYou 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.
With this code you can use any Class Mixin from others module for add other functions like permission supports or loggeer configurations.
I don’t like coding functional view so I only code ClassViews ↩︎
This post is part of the Django Tricks series
- Django Rest Framework: Multiple post
- Make a Excel Django combo
- Django With Barcode and Qrcode
- Django Return Pdf With Reportlab
- Django List View With Show More
- Message and Allert With Django and Boostrap
- Csv From Django
- Django Generate Barcode With Reportlab
- Add Minor Things to Django for templating
- Htmx Django and Django Table2
Reference this post
Please reference this post with a link to this page. I prefer to be called Fundor333 (he/him) or Fundor333' Blog.
Comments
To reply to this post, you can send a Webmention or you can toot me at [email protected]