Csv From Django

Csv From Django
by IA Midjourney

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 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.

With this code you can use any Class Mixin from others module for add other functions like permission supports or loggeer configurations.


  1. I don’t like coding functional view so I only code ClassViews ↩︎

Written by a human

Part of the series: Django Tricks
  1. Django Rest Framework: Multiple post
  2. Make a Excel Django combo
  3. Django With Barcode and Qrcode
  4. Django Return Pdf With Reportlab
  5. Django List View With Show More
  6. Message and Allert With Django and Boostrap
  7. Csv From Django
  8. Django Generate Barcode With Reportlab
  9. Add Minor Things to Django for templating
  10. Htmx Django and Django Table2
  11. Django Table, Filter and Export With Htmx
Reference this post

Please reference this post with a link to this page. I prefer to be called Fundor333 (he/him) or Fundor333' Blog.

Learn more

Comments

Reply with a Webmention or a reply on the Fediverse.

See also