📜  django admin 只读模型 - Python 代码示例

📅  最后修改于: 2022-03-11 14:45:05.229000             🧑  作者: Mango

代码示例1
"""
source: https://archive.is/AiLh1
license: https://archive.is/iCoSO
"""


class ReadOnlyAdminMixin:
    """Disables all editing capabilities."""
    change_form_template = "admin/view.html"

    def __init__(self, *args, **kwargs):
        super(ReadOnlyAdminMixin, self).__init__(*args, **kwargs)
        self.readonly_fields = [f.name for f in self.model._meta.get_fields()]

    def get_actions(self, request):
        actions = super(ReadOnlyAdminMixin, self).get_actions(request)
        actions.pop("delete_selected", None)
        return actions

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def save_model(self, request, obj, form, change):
        pass

    def delete_model(self, request, obj):
        pass

    def save_related(self, request, form, formsets, change):
        pass

@register(models.Address)
class AddressAdmin(ReadOnlyAdminMixin, admin.ModelAdmin):
    list_display = ('country', 'state', 'city', 'zipcode')
    search_fields = ('country', 'state', 'city', 'zipcode')
    list_filter = ('country', 'state')