From 1fb3f15124b3163f1edac14bde7595251e417d93 Mon Sep 17 00:00:00 2001 From: Atul Varma Date: Wed, 30 Jun 2021 23:23:15 -0400 Subject: [PATCH] Only show editable dashboards in admin changelist view. (#131) Thanks, Atul Varma --- django_sql_dashboard/admin.py | 7 +++++++ django_sql_dashboard/models.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/django_sql_dashboard/admin.py b/django_sql_dashboard/admin.py index 92f6c98..c9fef63 100644 --- a/django_sql_dashboard/admin.py +++ b/django_sql_dashboard/admin.py @@ -62,3 +62,10 @@ def get_readonly_fields(self, request, obj): if not request.user.is_superuser: readonly_fields.append("owned_by") return readonly_fields + + def get_queryset(self, request): + if request.user.is_superuser: + # Superusers should be able to see all dashboards. + return super().get_queryset(request) + # Otherwise, show only the dashboards the user has edit access to. + return Dashboard.get_editable_by_user(request.user) diff --git a/django_sql_dashboard/models.py b/django_sql_dashboard/models.py index 88e4fdc..f4f1c1e 100644 --- a/django_sql_dashboard/models.py +++ b/django_sql_dashboard/models.py @@ -103,6 +103,21 @@ def user_can_edit(self, user): return True return False + @classmethod + def get_editable_by_user(cls, user): + allowed_policies = [cls.EditPolicies.LOGGEDIN] + if user.is_staff: + allowed_policies.append(cls.EditPolicies.STAFF) + if user.is_superuser: + allowed_policies.append(cls.EditPolicies.SUPERUSER) + return ( + cls.objects.filter( + models.Q(owned_by=user) + | models.Q(edit_policy__in=allowed_policies) + | models.Q(view_policy=cls.EditPolicies.GROUP, edit_group__user=user) + ) + ).distinct() + @classmethod def get_visible_to_user(cls, user): allowed_policies = [cls.ViewPolicies.PUBLIC, cls.ViewPolicies.LOGGEDIN]