So you’ve started working with Django and you love the admin interface that you get for free with your models. You deploy half of your app with the admin interface and are about to release when you figure out that anyone who can modify a model can do anything with it. There is no concept of “ownership” of records!
Let me give you an example. Let’s say we’re creating a little MIS for the computer science department where each faculty member can put in his courses and record the course execution (what was done per lecture). That would be a nice application. (In fact, it’s available open source on github and that is what this tutorial is referring to.) However, the issue is that all instructors can access all the course records and there is no way of ensuring that an instructor can modify only the courses that s/he taught. This isn’t easily possible because admin doesn’t not have “row-level permissions”.
Of course, we can create them by sub-classing some of the Admin classes and modifying a couple of functions. Here’s how:
Let’s assume we have the following in our models:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
And in admin.py, we have the following:
1 2 3 4 5 6 7 8 9 10
So, when you open the page for Course, you can see the instructors and when you open the CourseOutline, you can see the Courses. Pretty good but how do we add row-level permissions? We do this by overriding a couple of functions.
Here’s the strategy I followed:
First, create a user account for each instructor. Then, take away these user’s rights to modify Instructor objects. (You can keep stuff in Instructor Profile so that they can modify their information.)
Next, add a field to the Instructor model that binds it to a particular user. The model now becomes:
1 2 3 4 5 6 7
The other models can remain the same. We only need to modify their “querysets”. Let’s open up admin.py again and modify the *Admins.
We override two functions to make CourseAdmin look like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
What’s that? The first function basically modifies the queryset function and makes sure that if you’re not a super user, you will see only those courses in the course list where
instructor__owner=request.user i.e. your own courses.
The second function is required so that you can’t add courses that belong to other instructors. It filters the foreign key dropdown box so that only
owner=request.user objects are shown in the foreign key dropdown. That is, you only see yourself in that dropdown.
We can do the same thing for CourseOutline. That is here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The only difference is that we’re now going two levels up the foreign key ladder. That’s all you need to have row-level permissions in admin. Questions?