Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :param database: The database where the unique check will be performed
(check_db=True, database=DEFAULT_DB_ALIAS)
| 244 | |
| 245 | |
| 246 | def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS): |
| 247 | """ |
| 248 | Try to determine the current system user's username to use as a default. |
| 249 | |
| 250 | :param check_db: If ``True``, requires that the username does not match an |
| 251 | existing ``auth.User`` (otherwise returns an empty string). |
| 252 | :param database: The database where the unique check will be performed. |
| 253 | :returns: The username, or an empty string if no username can be |
| 254 | determined or the suggested username is already taken. |
| 255 | """ |
| 256 | # This file is used in apps.py, it should not trigger models import. |
| 257 | from django.contrib.auth import models as auth_app |
| 258 | |
| 259 | # If the User model has been swapped out, we can't make any assumptions |
| 260 | # about the default user name. |
| 261 | if auth_app.User._meta.swapped: |
| 262 | return "" |
| 263 | |
| 264 | default_username = get_system_username() |
| 265 | try: |
| 266 | default_username = ( |
| 267 | unicodedata.normalize("NFKD", default_username) |
| 268 | .encode("ascii", "ignore") |
| 269 | .decode("ascii") |
| 270 | .replace(" ", "") |
| 271 | .lower() |
| 272 | ) |
| 273 | except UnicodeDecodeError: |
| 274 | return "" |
| 275 | |
| 276 | # Run the username validator |
| 277 | try: |
| 278 | auth_app.User._meta.get_field("username").run_validators(default_username) |
| 279 | except exceptions.ValidationError: |
| 280 | return "" |
| 281 | |
| 282 | # Don't return the default username if it is already taken. |
| 283 | if check_db and default_username: |
| 284 | try: |
| 285 | auth_app.User._default_manager.db_manager(database).get( |
| 286 | username=default_username, |
| 287 | ) |
| 288 | except auth_app.User.DoesNotExist: |
| 289 | pass |
| 290 | else: |
| 291 | return "" |
| 292 | return default_username |