Fixes #20342: Override create_superuser to drop is_staff (#20351)
Some checks are pending
CI / build (20.x, 3.12) (push) Waiting to run
CI / build (20.x, 3.13) (push) Waiting to run
CodeQL / Analyze (${{ matrix.language }}) (none, actions) (push) Waiting to run
CodeQL / Analyze (${{ matrix.language }}) (none, javascript-typescript) (push) Waiting to run
CodeQL / Analyze (${{ matrix.language }}) (none, python) (push) Waiting to run

* fix(users): Override create_superuser to drop is_staff

Override `UserManager.create_superuser()` to strip `is_staff` from
`extra_fields` and enforce `is_superuser=True`, fixing the `TypeError`
during `createsuperuser` with the custom `User` model.

Fixes #20342

* Set alters_data=True on manager methods

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
This commit is contained in:
Martin Hauser 2025-09-15 20:36:51 +02:00 committed by GitHub
parent 24fff6bd74
commit b4eaeead13
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -3,7 +3,7 @@ from django.contrib.auth.models import (
GroupManager as DjangoGroupManager,
Permission,
PermissionsMixin,
UserManager as DjangoUserManager
UserManager as DjangoUserManager,
)
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.core.exceptions import ValidationError
@ -74,9 +74,37 @@ class Group(models.Model):
class UserManager(DjangoUserManager.from_queryset(RestrictedQuerySet)):
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_superuser", False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, email, password, **extra_fields)
create_user.alters_data = True
async def acreate_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return await self._acreate_user(username, email, password, **extra_fields)
acreate_user.alters_data = True
def create_superuser(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, email, password, **extra_fields)
create_superuser.alters_data = True
async def acreate_superuser(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return await self._acreate_user(username, email, password, **extra_fields)
acreate_superuser.alters_data = True
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(