"""
Audit filters may be used in the Django Admin to create list filters using the full name of the user.
"""
# Imports
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from superdjango.conf import SUPERDJANGO
from superdjango.shortcuts import get_user_name
UserModel = get_user_model()
# Exports
__all__ = (
"BaseAuditListFilter",
"AddedByListFilter",
"ModifiedByListFilter",
"ViewedByListFilter",
)
# List Filters
[docs]class BaseAuditListFilter(admin.SimpleListFilter):
"""Base class for creating list filters based on user audit fields.
**Order By**
Ordering for the lookup defaults to ``USERNAME_FIELD``. You can change this by setting
``SUPERDJANGO_ORDER_USERS_BY`` in your ``settings.py`` file.
**Implementation**
When extending, set the ``parameter_name`` to the name of the audit field.
"""
[docs] def lookups(self, request, model_admin):
qs = UserModel.objects.all().order_by(SUPERDJANGO.USER_ORDER_USERS_BY)
a = list()
for user in qs:
a.append((user.pk, get_user_name(user)))
return a
[docs] def queryset(self, request, queryset):
lookup = "%s__pk" % self.parameter_name
criteria = {lookup: self.value()}
if self.value() is not None:
return queryset.filter(**criteria)
[docs]class AddedByListFilter(BaseAuditListFilter):
"""Filter for ``added_by``."""
title = _("Added By")
parameter_name = "added_by"
[docs]class ModifiedByListFilter(BaseAuditListFilter):
"""Filter for ``modified_by``."""
title = _("Modified By")
parameter_name = "modified_by"
[docs]class ViewedByListFilter(BaseAuditListFilter):
"""Filter for ``viewed_by``."""
title = _("Viewed By")
parameter_name = "viewed_by"