Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Last active December 16, 2022 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumepiot/8473955 to your computer and use it in GitHub Desktop.
Save guillaumepiot/8473955 to your computer and use it in GitHub Desktop.
PYTHON / DJANGO - CSV Export view
def export_profile(request):
import csv, StringIO, datetime
date = datetime.datetime.now()
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="profiles-%s.csv"' % (date.strftime('%d-%m-%Y'))
writer = csv.writer(response)
headers = (
('id', 'ID'),
('first_name', 'First Name'),
('last_name', 'Last Name'),
)
# Write headers line
row = []
for field in headers:
row.append(field[1])
writer.writerow(row)
profiles = Profile.objects.all()
for p in profiles:
row = []
# Add the profile field as new CSV column
for field in headers:
row.append(unicode(p.__dict__[field[0]]).encode('utf-8'))
writer.writerow(row)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment