Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export audit events to CSV #254

Merged
merged 1 commit into from
Jun 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions easyaudit/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
import csv, datetime

try: # Django 2.0
from django.urls import reverse
Expand All @@ -16,6 +18,30 @@
CRUD_EVENT_SEARCH_FIELDS, LOGIN_EVENT_SEARCH_FIELDS, REQUEST_EVENT_SEARCH_FIELDS,
READONLY_EVENTS)

# Export event audits to csv
def export_to_csv(modeladmin, request, queryset):
opts = modeladmin.model._meta
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;' 'filename={}.csv'.format(opts.verbose_name)
writer = csv.writer(response)
fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many]
# Write a first row with header information
writer.writerow([field.verbose_name for field in fields])
# Write data rows
for obj in queryset:
data_row = []
for field in fields:
value = getattr(obj, field.name)
if isinstance(value, datetime.datetime):
value = value.strftime('%d/%m/%Y')
data_row.append(value)
writer.writerow(data_row)

return response

export_to_csv.short_description = 'Export to CSV' #short description


# CRUD events
class CRUDEventAdmin(EasyAuditModelAdmin):
list_display = ['get_event_type_display', 'get_content_type', 'object_id', 'object_repr_link', 'user_link', 'datetime']
Expand Down Expand Up @@ -71,6 +97,7 @@ def changed_fields_prettified(self, obj):

changed_fields_prettified.short_description = 'changed fields'

actions = [export_to_csv]

if settings.ADMIN_SHOW_MODEL_EVENTS:
admin.site.register(CRUDEvent, CRUDEventAdmin)
Expand All @@ -96,6 +123,7 @@ def get_username(self, obj):

get_username.short_description = "User name"

actions = [export_to_csv]

if settings.ADMIN_SHOW_AUTH_EVENTS:
admin.site.register(LoginEvent, LoginEventAdmin)
Expand All @@ -114,6 +142,7 @@ def get_user(self, obj):

get_user.short_description = "User"

actions = [export_to_csv]

if settings.ADMIN_SHOW_REQUEST_EVENTS:
admin.site.register(RequestEvent, RequestEventAdmin)