def sync_ldap_users(self, ldap_users):
        """
        Synchronize users with local user database.
        """
        model = get_user_model()
        attributes = getattr(settings, 'LDAP_SYNC_USER_ATTRIBUTES', None)
        username_field = getattr(settings, 'LDAP_SYNC_USERNAME_FIELD', None)
        if username_field is None:
            username_field = getattr(model, 'USERNAME_FIELD', 'username')

        if not model._meta.get_field(username_field).unique:
            error_msg = ("Username field '%s' must be unique" % username_field)
            raise ImproperlyConfigured(error_msg)

        if username_field not in attributes.values():
            error_msg = ("LDAP_SYNC_USER_ATTRIBUTES must contain the "
                         "username field '%s'" % username_field)
            raise ImproperlyConfigured(error_msg)

        for cname, attrs in ldap_users:
            # In some cases with AD, attrs is a list instead of a
            # dict; these are not valid users, so skip them
            try:
                items = attrs.items()
            except AttributeError:
                continue

            # Extract user attributes from LDAP response
            user_attr = {}
            for name, attr in items:
                user_attr[attributes[name]] = attr[0].decode('utf-8')

            try:
                username = user_attr[username_field]
                user_attr[username_field] = username.lower()
            except KeyError:
                logger.warning("User is missing a required attribute '%s'" %
                               username_field)
                continue

            kwargs = {
                username_field + '__iexact': username,
                'defaults': user_attr,
            }

            # Create or update user data in the local database
            try:
                user, created = model.objects.get_or_create(**kwargs)
            except (IntegrityError, DataError) as e:
                logger.error("Error creating user %s: %s" % (username, e))
            else:
                updated_fields = []
                if created:
                    logger.debug("Created user %s" % username)
                    user.set_unusable_password()
                    updated_fields.append('password')
                else:
                    for name, attr in user_attr.items():
                        current_attr = getattr(user, name)
                        if current_attr != attr:
                            setattr(user, name, attr)
                            updated_fields.append(name)
                user.save(update_fields=updated_fields)

        logger.info("Users are synchronized")
dataset/ETHPy150Open jbittel/django-ldap-sync/ldap_sync/management/commands/syncldap.py/Command.sync_ldap_users/original