* type: Bug => Cleanup/optimization
* stage: Unreviewed => Accepted
Comment:
Thanks for this report. It's
[https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD
documented] that ''"The field must be unique (i.e., have **unique=True**
set in its definition)"'', however I agree that we could improve this,
e.g.:
{{{#!diff
diff --git a/django/contrib/auth/management/commands/createsuperuser.py
b/django/contrib/auth/management/commands/createsuperuser.py
index 5fffa55a22..0b8c72e866 100644
--- a/django/contrib/auth/management/commands/createsuperuser.py
+++ b/django/contrib/auth/management/commands/createsuperuser.py
@@ -11,6 +11,7 @@ from django.contrib.auth.password_validation import
validate_password
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
+from django.utils.functional import cached_property
from django.utils.text import capfirst
@@ -277,9 +278,18 @@ class Command(BaseCommand):
else "",
)
+ @cached_property
+ def username_is_unique(self):
+ if self.username_field.unique:
+ return True
+ for unique_constraint in
self.UserModel._meta.total_unique_constraints:
+ if len(unique_constraint.fields) == 1 and
self.username_field.name == unique_constraint.fields[0]:
+ return True
+ return False
+
def _validate_username(self, username, verbose_field_name, database):
"""Validate username. If invalid, return a string error
message."""
- if self.username_field.unique:
+ if self.username_is_unique:
try:
self.UserModel._default_manager.db_manager(database).get_by_natural_key(
username
}}}
Would you like to prepare a patch? (a regression test is also required.)
--
Ticket URL: <https://code.djangoproject.com/ticket/33613#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.