Merge pull request #4836 from foarsitter/mypy_generic_user_manager

Generic UserManager
This commit is contained in:
Jelmer 2024-02-07 15:16:22 +01:00 committed by GitHub
commit df730044b2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 4 deletions

View File

@ -1,8 +1,13 @@
from typing import TYPE_CHECKING
from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import UserManager as DjangoUserManager from django.contrib.auth.models import UserManager as DjangoUserManager
if TYPE_CHECKING:
from {{ cookiecutter.project_slug }}.users.models import User # noqa: F401
class UserManager(DjangoUserManager):
class UserManager(DjangoUserManager["User"]):
"""Custom manager for the User model.""" """Custom manager for the User model."""
def _create_user(self, email: str, password: str | None, **extra_fields): def _create_user(self, email: str, password: str | None, **extra_fields):
@ -17,12 +22,12 @@ class UserManager(DjangoUserManager):
user.save(using=self._db) user.save(using=self._db)
return user return user
def create_user(self, email: str, password: str | None = None, **extra_fields): def create_user(self, email: str, password: str | None = None, **extra_fields): # type: ignore[override]
extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False) extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields) return self._create_user(email, password, **extra_fields)
def create_superuser(self, email: str, password: str | None = None, **extra_fields): def create_superuser(self, email: str, password: str | None = None, **extra_fields): # type: ignore[override]
extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_superuser", True)

View File

@ -1,3 +1,7 @@
{%- if cookiecutter.username_type == "email" %}
from typing import ClassVar
{%- endif %}
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from django.db.models import CharField{% if cookiecutter.username_type == "email" %}, EmailField{% endif %} from django.db.models import CharField{% if cookiecutter.username_type == "email" %}, EmailField{% endif %}
from django.urls import reverse from django.urls import reverse
@ -26,7 +30,7 @@ class User(AbstractUser):
USERNAME_FIELD = "email" USERNAME_FIELD = "email"
REQUIRED_FIELDS = [] REQUIRED_FIELDS = []
objects = UserManager() objects: ClassVar[UserManager] = UserManager()
{%- endif %} {%- endif %}
def get_absolute_url(self) -> str: def get_absolute_url(self) -> str: