DJANGO – 25 EXPORTING DATABASE CONTENT TO CSV

Spread the love

1. Add export to CSV checkbox to your model or form

export_to_CSV = models.BooleanField(default=False)

2. Do makemigration and migrate:

3. In forms.py, update for the field to include “export_to_CSV”

export_to_CSV = forms.BooleanField(required=False, label="Export to CSV")

4. In views.py, import HttpResponse from django.http, and csv

from django.http import HttpResponse
import csv

5. Past the following line in the condition that when fulfilled, the following line will run

if form['export_to_CSV'].value() == True:
     response = HttpResponse(content_type='text/csv')
     response['Content-Disposition'] = 'attachment; filename="Computer list.csv"'
     writer = csv.writer(response)
     writer.writerow(['COMPUTER NAME', 'IP Address', 'MAC ADDRESS', 'OS', 'USERNAME', 'LOCATION', 'PURCHASE DATE', 'TIMESTAMP'])
     instance = queryset
     for row in instance:
         writer.writerow([row.computer_name, row.IP_address, row.MAC_address, row.operating_system.all(), row.users_name, row.location, row.purchase_date, row.timestamp])
     return response

Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *