Search code examples
pythonpython-3.xdjangodjango-admindjango-admin-actions

What is the best practice / best place for enabling/disabling site-wide admin functionality


Situation: I have a Django project with multiple applications, each of which have one or more models. I have added custom admin actions for some of the models and got the "Delete selected" action for free. I want to disable this for all models in all applications.

I'm aware how to disable the "Delete selected" action for the whole project, i.e. by using

admin.site.disable_action('delete_selected')

but I simply don't know where to put it. I've put it in the admin.py file of one application and that definitely works, but that bugs me as (in my opinion) a site-wide change, also affecting other applications, shouldn't be caused by the admin configuration of a single application. I was hoping to find some way to have a "project-level" admin.py file, but it seems that only fully customizing the AdminSite will do the trick, which I think is a bit overkill if I only want to disable the "delete_selected" action globally.

Any thoughts?


Solution

  • It's somewhat up to you, but to do that where you are already importing the necessary module would make sense.

    It's likely you could do this in your project urls.py, and taking one of mine as an example you'd do;

    
    from django.contrib import admin
    from django.urls import re_path, path, include
    from django.views.decorators.cache import cache_page
    from django.views.i18n import JavaScriptCatalog
    
    
    try:
        admin.site.disable_action('delete_selected')
    except KeyError:
        pass
    
    
    urlpatterns = [
    
        path(
            'jsi18n/',
            cache_page(60 * 60, cache='pages')(
                JavaScriptCatalog.as_view()
            ),
            name='javascript-catalog'
        ),
        path(
            'admin/',
            admin.site.urls
        )
    ]
    

    I've wrapped it in a try/except because I've seen a KeyError when testing this.