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

前端 未结 9 1215
眼角桃花
眼角桃花 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:14

    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)
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-24 08:20

    This has been possible for a while. The names are has_add_permission, has_change_permission and has_delete_permission. See the django admin documentation for reference. Here is also an example:

    @admin.register(Object)
    class Admin(admin.ModelAdmin):
    
        def has_add_permission(self, request):
            return False
    
        def has_change_permission(self, request, obj=None):
            return False
    
        def has_delete_permission(self, request, obj=None):
            return False
    
    0 讨论(0)
提交回复
热议问题