How to set Django admin models into Read Only mode


This is common question we need to showing models of app inside django admin but in read-only mode. That’s meaning admin only can see but can’t modify. For instance, I have models called Insurance :

1
2
3
4
class InsuranceBranch(models.ModelAdmin):
    country = models.ForeignKey(Country)
    created = models.DateTimeField(auto_now_add=True, default=datetime.now())
    modified = models.DateTimeField(auto_now=True, default=datetime.now())

Then, I want to show it into Django admin, so inside admins.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class InsuranceBranchAdmin(admin.ModelAdmin):
    list_display = ["country"]
    readonly_fieds = ("country",)
   
    def get_readonly_fields(self, request, obj=None):
        return self.readonly_fieds

    def has_add_permission(self, request):
        return False

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

admin.site.register(InsuranceBranch, InsuranceBranchAdmin)

What this code mean? basically, you need to set readonly_fields to tell Django admin to set this fields into read-only mode.
For has_add_permission and has_delete_permission, we make it to False to keep no data created / deleted.

And the last thing is, set get_readonly_fields() to return readonly_fields to make on Change Page, all become read-only. Simple 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.