-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1342 from glogiotatidis/issue-1204-csv-export
[Fix #1204] Add CSV Export action to metrics related adminmodels.
- Loading branch information
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,30 @@ | ||
import csv | ||
from datetime import datetime | ||
|
||
from django.db import transaction | ||
from django.http import HttpResponse | ||
|
||
|
||
@transaction.atomic | ||
def duplicate_snippets_action(modeladmin, request, queryset): | ||
for snippet in queryset: | ||
snippet.duplicate(request.user) | ||
duplicate_snippets_action.short_description = 'Duplicate selected snippets' # noqa | ||
|
||
|
||
def export_as_csv(modeladmin, request, queryset): | ||
"""Adapted from https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html""" | ||
meta = modeladmin.model._meta | ||
field_names = [field.name for field in meta.fields] | ||
filename = f'{meta}-{datetime.today().strftime("%Y-%m-%d-%H-%M")}' | ||
|
||
response = HttpResponse(content_type='text/csv') | ||
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(filename) | ||
writer = csv.writer(response) | ||
|
||
writer.writerow(field_names) | ||
for obj in queryset: | ||
writer.writerow([getattr(obj, field) for field in field_names]) | ||
|
||
return response | ||
export_as_csv.short_description = 'Export Selected to CSV' # noqa |
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