Csv From Django

Fundor333 | | Reading time 1 minutes | Word count 153

####


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 ↩︎

This post is part of the Django Tricks series
  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



Comments

To reply to this post, you can send a Webmention or you can toot me at [email protected]
You mentioned this post on your site? Send a Webmention


See Also