This makes the change from everything specifying AbstractUser to AbstractBaseUser and additionally adds in corrections for when the user may be None or a django.contrib.auth.models.AnonymousUser. It is common to subclass AbstractBaseUser rather than AbstractUser to do things such as provide a model with only an email address field which serves the purpose of the username, customizing fields used for storing the user's name, etc.
Since I saw the pipe operator for union types in use already in at least once place, I updated any annotations I touched which were using Optional[AbstractUser] to instead use AbstractBaseUser | None. This functionality was not added until Python 3.10, so I also added the __future__ import of annotations so that what is currently considered the preferred way of handling these annotations can be used until Python 3.9 reaches its end of life. There are still one or two places using Optional[Whatever], it might be worth updating them for consistency.
This makes the change from everything specifying
AbstractUser
toAbstractBaseUser
and additionally adds in corrections for when the user may beNone
or adjango.contrib.auth.models.AnonymousUser
. It is common to subclassAbstractBaseUser
rather thanAbstractUser
to do things such as provide a model with only an email address field which serves the purpose of the username, customizing fields used for storing the user's name, etc.Subclassing
AbstractBaseUser
is also what is recommended in the django docs for providing a custom user model. https://docs.djangoproject.com/en/5.0/topics/auth/customizing/#specifying-a-custom-user-model. This is also whatdjango-stubs
specifies as being returned byget_user_model()
at https://github.com/typeddjango/django-stubs/blob/e41ffedd0fcfdd04a59ebe3a69b755927e87da62/django-stubs/contrib/auth/__init__.pyi#L31Since I saw the pipe operator for union types in use already in at least once place, I updated any annotations I touched which were using
Optional[AbstractUser]
to instead useAbstractBaseUser | None
. This functionality was not added until Python 3.10, so I also added the__future__
import ofannotations
so that what is currently considered the preferred way of handling these annotations can be used until Python 3.9 reaches its end of life. There are still one or two places usingOptional[Whatever]
, it might be worth updating them for consistency.