Last active
December 16, 2022 15:31
-
-
Save guillaumepiot/8473955 to your computer and use it in GitHub Desktop.
PYTHON / DJANGO - CSV Export view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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