Issue
I have enabled Log entries in the Django Admin
class CustomLogEntryAdmin(admin.ModelAdmin):
list_display = [
"action_time",
"user",
"content_type",
"object_id",
"object_repr",
"action_flag",
"change_message",
]
# list filter
list_filter = ["action_time", "user", "content_type"]
# search
search_fields = ["user__username", "object_repr"]
admin.site.register(LogEntry, CustomLogEntryAdmin)
And I have another model whose admin.py code is like this
class RegAdmin(ExportActionMixin, admin.ModelAdmin):
resource_class = RegAdminResource
def has_view_permission(self, request, obj=None):
return True
def has_module_permission(self, request):
return True
By default all change, addition and deletion entries are logged but I also want to log an entry when any export action is performed on it. ChatGPT suggests that I should something like this
# in admin class
def export_action(self, request, *args, **kwargs):
# Log the export action
LogEntry.objects.create(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(self.model).id,
object_id=None,
object_repr=str(self.model),
action_flag=1, # Assuming 1 stands for the action flag of 'change'
change_message="Export action triggered.",
)
return super().export_action(request, *args, **kwargs)
But this function is not triggered when an export action is performed. I confirmed by adding a print statement.
How should I do this?
Solution
You are quite close, the only problem is that the actions have reference to the one defined in the ExportActionMixin
, so you can override whatever you want, it is not going to refer to your method. You can however override that to to get the right action, so:
from django.utils.translation import gettext as _
class RegAdmin(ExportActionMixin, admin.ModelAdmin):
# …
def get_actions(self, request):
actions = super().get_actions(request)
actions.update(
export_admin_action=(
RegAdmin.export_admin_action,
'export_admin_action',
_('Export selected %(verbose_name_plural)s'),
)
)
return actions
Update: I've opened a pull request [GitHub] to fix this behavior.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.