Repository: django/django
File: django/contrib/auth/management/__init__.py (Python)

Code before:
        # entry in the /etc/passwd file (for example, in a very restricted
        # chroot environment).
        return ""
    return result


def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS):
    """
    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.
    :returns: The username, or an empty string if no username can be
        determined or the suggested username is already taken.
    """
    # This file is used in apps.py, it should not trigger models import.
    from django.contrib.auth import models as auth_app

    # If the User model has been swapped out, we can't make any assumptions
    # about the default user name.
    if auth_app.User._meta.swapped:
        return ""

    default_username = get_system_username()
    try:
        default_username = (
            unicodedata.normalize("NFKD", default_username)
            .encode("ascii", "ignore")
            .decode("ascii")
            .replace(" ", "")
            .lower()
        )
    except UnicodeDecodeError:
        return ""

    # Run the username validator
    try:
        auth_app.User._meta.get_field("username").run_validators(default_username)
    except exceptions.ValidationError:
        return ""

    # Don't return the default username if it is already taken.
    if check_db and default_username:
        try:
            auth_app.User._default_manager.db_manager(database).get(
                username=default_username,
            )
        except auth_app.User.DoesNotExist:
            pass
        else:

Review comment (suggestion):
This could use a comment explaining under what circumstances `IntegrityError` happens.

Code after:
    def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model("contenttypes", "ContentType")
        # Use the live Permission model instead of the frozen one, since frozen
        # models do not retain foreign key constraints.
        from django.contrib.auth.models import Permission

        db = schema_editor.connection.alias
        ctypes = ContentType.objects.filter(
            app_label=self.app_label, model__icontains=old_model.lower()
        )
        for permission in Permission.objects.filter(
            content_type_id__in=ctypes.values("id")
        ):
            prefix = permission.codename.split("_")[0]
            default_verbose_name = camel_case_to_spaces(new_model)

            new_codename = f"{prefix}_{new_model.lower()}"
            new_name = f"Can {prefix} {default_verbose_name}"

            if permission.codename != new_codename or permission.name != new_name:
                permission.codename = new_codename
                permission.name = new_name
                try:
                    with transaction.atomic(using=db):
                        permission.save(update_fields={"name", "codename"})
                except IntegrityError:
                    pass

    def rename_forward(self, apps, schema_editor):
        self._rename(apps, schema_editor, self.old_model, self.new_model)

    def rename_backward(self, apps, schema_editor):
        self._rename(apps, schema_editor, self.new_model, self.old_model)


def rename_permissions(
    plan,
    verbosity=2,
    interactive=True,
    using=DEFAULT_DB_ALIAS,
    apps=global_apps,
    **kwargs,
):
    """
    Insert a `RenamePermissionType` operation after every planned `RenameModel`
    operation.
    """
    try:
        Permission = apps.get_model("auth", "Permission")
    except LookupError:
        return