Seves
Seves

Reputation: 165

Django Admin: Show different models to different users

I have two superusers (user1 and user2) and two models (ModelA and ModelB). In the admin page, I want to show just ModelA to user1, so user1 can only edit ModelA instances but not ModelB instances. Similarly, I want to have user2 able to edit ModelB instances only. Is there a way to achieve this?

Upvotes: 2

Views: 2099

Answers (3)

shahwan42
shahwan42

Reputation: 75

in has_module_permission you can do the following:

def has_module_permission(self, request):
    if request.user.is_superuser:  # show for super user anyway
        return True
    if request.user ... complete the condition:
        return True

you should have something to differentiate between users, like having more attributes for different users (admin, staff, editors) and so on.

if request.user.role = "staff":
    return True

something like that.

Upvotes: 1

Raja Simon
Raja Simon

Reputation: 10305

That's what the has_change_permission is for. You can grant edit permission to specific users.

class TestAdmin(admin.ModelAdmin):

    def has_change_permission(self, request):
        if request.user.username == 'xyz':
            # Feel free to return false to hide this TestAdmin to xyz user
            return False
        return True

Upvotes: 1

mrehan
mrehan

Reputation: 1182

user1 and user2 cannot be superusers if you need to limit their access to ModelA and ModelB respectively. So, please refactor that first.

Yes, you can give specific users to specific models access in Django admin interface. Please have a look at Django docs: Permissions and Authorizations.

There is also a good tutorial on setting up permissions and groups at: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication

Let me know if you have confusions after reading along the resources.

Thanks!

Upvotes: 0

Related Questions