[Django]-How to restrict access for staff users to see only their information in Django admin page?

13๐Ÿ‘

โœ…

You can set superusers to only have add/delete permissions in the admin class.

class UserAdmin(BaseUserAdmin):
    ...
    def has_add_permission(self, request, obj=None):
        return request.user.is_superuser

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

Note the above is also achievable by not granting the add or delete permissions to any group or user in the admin interface.

The following will only allow users to change all users if they are a superuser. Else they will only be able to change their own user.

    def has_change_permission(self, request, obj=None):
        return request.user.is_superuser or (obj and obj.id == request.user.id)

And if you want them to be able to see the user list page with only their user visible you can modify get_queryset

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        user = request.user
        return qs if user.is_superuser else qs.filter(id=user.id)
๐Ÿ‘คMikey Lockwood

0๐Ÿ‘

In your template:

{% if request.user.is_superuser %}
<!-- Only superusers can view things in here -->
{% endif %}

In your view, you also will have to control what can be edited and what cannot be.

๐Ÿ‘คSam Creamer

Leave a comment