I was in a meeting where I was asked to give someone read-only access to the Admin part of our application. That was fine -- it was written in Django and Django has really fantastic Admin functionality. So I assumed that it could handle it, no problem. So I said yes.
Of course, after a little googling, I found that that it doesn't support this at all -- you can only give people Add, Change, or Delete permissions. You can make individual fields read-only but, in an ideal world, I needed a whole object to be read-only or not, hopefully determined by Group membership.
My searches didn't give me a lot of hope, but I did find something close [in this post.][]. So I expanded it to look for a Group.
So you used ReadOnlyAdmin
to inherit from instead of ModelAdmin
for all Admin objects you want to make read-only. Then you also have to add these two properties:
user_readonly
- list of the fields to be read-only. If you don't put in there, the user will be able to change the Model!user_readonly_inlines
- If you have a related Model that you want to display Inline, then you can't add it touser_readonly
because it's not part of the Model. You have create a read-only InlineAdmin object and list that here.
Creating a read-only Admin object is simple:
class MyModelInline(admin.StackedInline):
model =MyModel
class MyModelReadOnlyInline(MyModelInline):
readonly_fields = ["label",]
Then you just list MyModelReadOnlyInline
in the user_readonly_inlines
and MyModelInline
in inlines
.
To use the ReadOnlyAdmin
:
- Create a Admin Group called
readonly
. - Add the User to
readonly
and give them full access to the Models you want them to read -- yes, give them Add, Change, etc. Or they can't view them at all.
When the user logs in, they will see the Model and go to individual ones, but none of the fields will be in form fields -- just straight text.