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

前端 未结 9 1273
眼角桃花
眼角桃花 2020-12-24 07:39

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

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 08:20

    The easiest method would be disabling respective permissions in ModelAdmin class. For example, I have a Cart model that I want an admin to only view (list and details) and all I did was to add the following functions to CartAdmin class to disable delete, change and add

    class CartAdmin(admin.ModelAdmin):
        list_display = ['listing']
    
        def has_add_permission(self, request, obj=None):
            return False
    
        def has_change_permission(self, request, obj=None):
            return False
    
        def has_delete_permission(self, request, obj=None):
            return False
    

    The three methods has_add_permission, has_change_permission and has_delete_permission are the ones that disable add button, add form, edit form and delete buttons in the admin

    Here is a sample output when viewing a record details in the admin that has the above permissions disabled

    As you can see the diagram above, you only have close button and the details are not displayed in a form

提交回复
热议问题