Last active
May 18, 2021 04:42
-
-
Save pricco/24826bae3d5102d963eb13ecc0493f33 to your computer and use it in GitHub Desktop.
Django Admin: Request for list_display
This file contains hidden or 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
# any_app/admin.py | |
from django.contrib import admin | |
from core.admin_mixins import ModelAdminMixin | |
@admin.register(AnyModel) | |
class AnyModelAdmin(ModelAdminMixin, admin.ModelAdminMixin): | |
list_display = ['id', 'especial_display_with_request'] | |
def especial_display_with_request(self, obj, request): | |
# Make something special with the request | |
return obj.any_field | |
especial_display_with_request.needs_request = True # Similar to short_description or any other django admin attr. |
This file contains hidden or 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
# core/admin_mixins.py | |
from functools import partial, update_wrapper, lru_cache | |
# Django admin call 2 times get_list_display. | |
# We need to return the same function to make the method sortable using 'admin_order_field' | |
# https://github.com/django/django/blob/2161db0792f2e4d3deef3e09cd72f7a08340cafe/django/contrib/admin/templatetags/admin_list.py#L84 | |
@lru_cache(maxsize=100) | |
def cache_display_wrap(f, request): | |
wf = partial(f, request=request) | |
nf = update_wrapper(wf, f) | |
return nf | |
class ModelAdminMixin(admin.ModelAdmin): | |
def get_list_display(self, request): | |
def check_needs_request(display): | |
f = getattr(self, display, None) if not callable(display) else display | |
if f and getattr(f, 'needs_request', False): | |
return cache_display_wrap(f, request) | |
return display | |
return [check_needs_request(display) for display in super().get_list_display(request)] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment