Search code examples
pythonpython-3.xdjangodjango-modelsdjango-admin

Django Admin- disable Editing and remove "Save" buttons for a specific model


I have a Django Model which I wish to be only readonly. No adds and edits allowed.

I have marked all fields readonly and overridden has_add_permission in ModelAdmin as:

class SomeModelAdmin(admin.ModelAdmin):
     def has_add_permission(self, request):
        return False

Is there a similar has_edit_permission? Which can be disabled to remove "Save" and "Save and continue" buttons? And replace by a simple "Close and Return" button.

Django Documentation Only mentions only about read only fields not about overriding edit permissions.


Solution

  • Override the templates/admin/submit_line.html template and make the buttons whatever you want. You can do this for only the specific model by putting it in templates/admin/[app_label]/[model]/submit_line.html.

    To conditionally show the default submit line or your custom submit line, override ModelAdmin.change_view, and add a boolean to extra_context:

    class MyModelAdmin(admin.ModelAdmin):
        ...
        def change_view(self, request, object_id, extra_context=None):
            if not request.user.is_superuser:
                extra_context = extra_context or {}
                extra_context['readonly'] = True
    
            return super(MyModelAdmin, self).change_view(request, object_id, extra_context=extra_context)