Making Django admin models readonly with custom mixins

Very common case is to have some models in the Django admin which should be readonly. This article shows how to create a new mixin class to make a model or an inline readonly in the Django admin.

  • calendar_month 2.10.2024
  • pace 10 minutes

To make a model readonly in the Django admin, you can override the has_add_permission, has_change_permission, and has_delete_permission methods of the ModelAdmin class to return False. This will prevent adding, editing, and deleting of records in the admin interface thus it will make all the available fields readonly.

The following example shows how to make a model readonly in the Django admin. We are going to create a new mixin class ReadOnlyAdminMixin which will make possible to share the same admin class for different models as this tends to be a common case.

class ReadOnlyAdminMixin:
    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 next step is to create a new admin class for the model which will inherit from the ReadOnlyAdminMixin and from ModelAdmin. Make sure that the ReadOnlyAdminMixin is before ModelAdmin in the inheritance list.

from django.contrib.admin import ModelAdmin
from django.contrib.auth.admin import UserAdmin


@admin.register(User)
class UserAdmin(ReadOnlyAdminMixin, ModelAdmin):
    list_display = ["username", "email", "is_staff", "is_superuser"]

The same approach can be used for the inlines as well which will again make all the fields readonly. Below is an example of how to create a new inline admin class for the User model for TabularInline.

class UserInline(ReadOnlyAdminMixin, TabularInline):
    model = User
    fields = ["username", "email", "is_staff", "is_superuser"]

In Unfold, this mixin is going to work as well. The only difference is that Unfold is using different ModelAdmin class to define the admin class for the models so we have to inherit from unfold.admin.ModelAdmin instead of standard django.contrib.admin.ModelAdmin.

Django admin theme built with Tailwind CSS to bring modern look and feel to your admin interface. Already contains several built-in features for smooth developer experience.

© 2023 - 2025 Created by unfoldadmin.com. All rights reserved.