Atma
Atma

Reputation: 29767

how to show records related to a certain user in django admin

I want to create a way for users to only be able to edit/add objects (Company objects) related with the logged in user.

Currently all logged in users are able to edit all Companys even when I create permissions to:

Company | Can Add Company
Company | Can Change Company

What can I add to the Admin.py to constrain a user to be able to to edit/add objects (Company objects) related with the logged in user?

Upvotes: 3

Views: 498

Answers (1)

Vladimir Danilov
Vladimir Danilov

Reputation: 2388

Maybe ModelAdmin.get_queryset() can help. You can use it to perform checks on the request.user object.

class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(MyModelAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

Upvotes: 3

Related Questions