0

I have an app 'app_name' which has a profile object which is linked to User object via OneToOne field way. Now on login I redirect the user to a edit profile page on admin site using url using his profile object id. I've granted as expected is_staff access and permission to edit profiles.

Now I wan't to prevent him from accessing other profile objects. I've got two ways, as of now, which I can think so- 1. Make a custom permission which grants access to edit for his profile only who logins. 2. Blocking urls which doesn't involves profile object id.

Superuser should be able to access normally as it is available as default.

I've no idea how can I execute one of the ways. Any other possible ways are too welcomed. Please help!

CharcoalG
  • 185
  • 4
  • 12

1 Answers1

0

Override ModelAdmin.get_queryset() can exclude other objects:

class ProfileAdmin(ModelAdmin):
    # current user can only see his profile
    def get_queryset(self, request):
        qs = super(ProfileAdmin, self).get_queryset(request)
        if not request.user.is_superuser:
            qs = qs.filter(id=request.user.id)
        return qs

If you only want to control change permission, override ModelAdmin.has_change_permission():

class ProfileAdmin(ModelAdmin):
    # current user can only edit his profile
    def has_change_permission(self, request, obj=None):
        # user has permission to edit a obj
        if not obj or request.user.is_superuser:
            return True
        # user ONLY has permission to edit his obj
        return request.user.id == obj.user.id
JimmyYe
  • 844
  • 6
  • 6
  • First one not working for me. It's hardly making any difference. Second method gives a TypeError saying: "has_change_permission() takes at most 2 arguments (3 given)" – CharcoalG Oct 18 '15 at 15:58
  • Sorry, missed `self` in method definition. But the first one should work, a 404 will be raised when any user who is not superuser want to view other user's profile. The second one, while can control change permission, all user can view the change list. – JimmyYe Oct 18 '15 at 17:13