Skip to content
Open
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
24 changes: 24 additions & 0 deletions rest_framework_simplejwt/token_blacklist/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from django.contrib import admin
from django.contrib.auth.models import AbstractBaseUser
from django.core.management import call_command
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _
from rest_framework.request import Request
Expand Down Expand Up @@ -68,6 +69,29 @@ class BlacklistedTokenAdmin(admin.ModelAdmin):
)
ordering = ("token__user",)

@admin.action(permissions=["change"], description=_("Flush expired tokens"))
def flush_expired_tokens(self, request, queryset):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def flush_expired_tokens(self, request, queryset):
@admin.action(permissions=["change"], description = _("Flush expired tokens"))
def flush_expired_tokens(self, request, queryset):

What are your thoughts on using the @admin.action decorator?
It allows you to set the required permissions for executing an action and provides a description for it as well. Additionally, you can use gettext_lazy to provide localization support. @tpotjj

call_command("flushexpiredtokens")
self.message_user(request, "Flushed expired tokens.")

# Override the changelist_view method to bypass the "no items selected" validation
def changelist_view(self, request, extra_context=None):
"""
Override the default behavior to allow running the custom command
without explicitly selecting any items.
"""
if (
"action" in request.POST
and request.POST["action"] == "flush_expired_tokens"
):
# Modify the queryset to include all items
queryset = self.get_queryset(request)
self.flush_expired_tokens(request, queryset)
# Redirect to the changelist after running the command
return self.response_post_save_change(request, None)

return super().changelist_view(request, extra_context=extra_context)

def get_queryset(self, *args, **kwargs) -> QuerySet:
qs = super().get_queryset(*args, **kwargs)

Expand Down