From 6b17024397ef8a7b614e701e4786ff99a35d4ce8 Mon Sep 17 00:00:00 2001 From: oudeismetis Date: Thu, 12 Sep 2024 09:46:46 -0400 Subject: [PATCH] model manager for user --- .../{{cookiecutter.project_slug}}/core/models.py | 15 +++++++++++++++ .../{{cookiecutter.project_slug}}/core/views.py | 5 ++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/models.py b/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/models.py index c7cceee33..e803538e2 100644 --- a/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/models.py +++ b/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/models.py @@ -11,11 +11,26 @@ logger = logging.getLogger(__name__) +class UserQuerySet(models.QuerySet): + def for_user(self, user): + if not user or user.is_anonymous: + return self.none() + elif user.is_staff: + return self.all() + return self.filter(pk=user.pk) + + class UserManager(BaseUserManager): """Custom User model manager, eliminating the 'username' field.""" use_in_migrations = True + def get_queryset(self): + return UserQuerySet(self.model, using=self.db) + + def for_user(self, user): + return self.get_queryset().for_user(user) + def _create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. diff --git a/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/views.py b/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/views.py index 4557850af..449c1d420 100755 --- a/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/views.py +++ b/{{cookiecutter.project_slug}}/server/{{cookiecutter.project_slug}}/core/views.py @@ -61,8 +61,7 @@ def get_queryset(self): """ Users should only find themselves by default """ - user = self.request.user - return User.objects.filter(pk=user.pk) + return super().get_queryset().for_user(self.request.user) @transaction.atomic def create(self, request, *args, **kwargs): @@ -117,7 +116,7 @@ def request_reset_link(request, *args, **kwargs): def reset_password(request, *args, **kwargs): user_id = kwargs.get("uid") token = kwargs.get("token") - user = User.objects.filter(id=user_id).first() + user = User.objects.filter(pk=user_id).first() if not user or not token: raise ValidationError(detail={"non-field-error": "Invalid or expired token"}) is_valid = default_token_generator.check_token(user, token)