Django list_per_page for all models in admin

Viewed 2684

Good day! I'm trying to find the solution to add list_per_page as a global parameter for all models in admin. I found out, that ModelAdmin has this parameter through ChangeList object and it has default value 100. But what if I want to set it 20 and it will be true for all models? I mean, if I need to change list_per_page for current model in admin, I need to add:

class CurrentModelAdmin(models.ModelAdmin):
    list_per_page = 20
    ...

Is there any way to redefine ChangeList object to rewrite default value? For example as a LIST_PER_PAGE = 20 in a settings.py

And even better, how I can recieve it from frontend and work with that dynamicly?

1 Answers

Yes, you define a variable in your settings, for example:

# settings.py

# ...
LIST_PER_PAGE = 20

Alter individual ModelAdmin classes

then in your views you can write:

from django.conf import settings

class CurrentModelAdmin(models.ModelAdmin):
    list_per_page = settings.LIST_PER_PAGE

Define a baseclass with the list_per_page attribute set

It can be cumberome to write this for every ModelAdmin view, so you can for example first make a subclass that sets the list_per_page, and then subclass from that model:

from django.conf import settings

class BaseModelAdmin(models.ModelAdmin):
    list_per_page = settings.LIST_PER_PAGE

class CurrentModelAdmin(BaseModelAdmin):
    # ...
    pass

So now we do no longer need to specify the list_per_page attribute in every ModelAdmin, as long as we subclass from the BaseModelAdmin.

Monkey patch the ModelAdmin class

You can also "monkey patch" the list_per_page attribute, and thus only update the value at the ModelAdmin level:

# app/monkey_patching.py

from django.conf import settings

ModelAdmin.list_per_page = settings.LIST_PER_PAGE

and follow the steps to "activate" the monkey patching in Django.

Related