Last active
August 7, 2022 19:39
-
-
Save aaugustin/1388243 to your computer and use it in GitHub Desktop.
Read-only ModelAdmin for Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
class ReadOnlyModelAdmin(admin.ModelAdmin): | |
""" | |
ModelAdmin class that prevents modifications through the admin. | |
The changelist and the detail view work, but a 403 is returned | |
if one actually tries to edit an object. | |
Source: https://gist.github.com/aaugustin/1388243 | |
""" | |
actions = None | |
# We cannot call super().get_fields(request, obj) because that method calls | |
# get_readonly_fields(request, obj), causing infinite recursion. Ditto for | |
# super().get_form(request, obj). So we assume the default ModelForm. | |
def get_readonly_fields(self, request, obj=None): | |
return self.fields or [f.name for f in self.model._meta.fields] | |
def has_add_permission(self, request): | |
return False | |
# Allow viewing objects but not actually changing them. | |
def has_change_permission(self, request, obj=None): | |
return (request.method in ['GET', 'HEAD'] and | |
super().has_change_permission(request, obj)) | |
def has_delete_permission(self, request, obj=None): | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, this gist no longer serves a purpose since the Django admin gained a "view" permission. Back then it didn't exist!