def sync_ldap_user_membership(self, user, ldap_groups):
        groupname_field = 'name'
        actualGroups = user.groups.values_list('name', flat=True)
        user_Membership_total = len(ldap_groups)
        user_Membership_added = 0
        user_Membership_deleted = 0
        user_Membership_errors = 0
        ldap_groups += self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_ADD_DEFAULT
        ldap_name_groups = []
        for cname, ldap_attributes in ldap_groups:
            defaults = {}
            try:
                for name, attribute in ldap_attributes.items():
                    defaults[self.conf_LDAP_SYNC_GROUP_ATTRIBUTES[name]] = attribute[0].decode('utf-8')
            except AttributeError:
                continue
            try:
                groupname = defaults[groupname_field]
                ldap_name_groups.append(groupname)
            except KeyError:
                logger.warning("Group is missing a required attribute '%s'" % groupname_field)
                user_Membership_errors += 1
                continue
            if (groupname not in actualGroups):
                kwargs = {
                    groupname_field + '__iexact': groupname,
                    'defaults': defaults,
                }
                try:
                    if (self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_CREATE_IF_NOT_EXISTS):
                        group, created = Group.objects.get_or_create(**kwargs)
                    else:
                        group = Group.objects.get(name=groupname)
                        created = False
                except (ObjectDoesNotExist):
                    continue
                except (IntegrityError, DataError) as e:
                    logger.error("Error creating group %s: %s" % (groupname, e))
                    user_Membership_errors += 1
                else:
                    if created:
                        logger.debug("Created group %s" % groupname)
                    group.user_set.add(user)
                    user_Membership_added += 1
        for check_group in actualGroups:
            if (check_group not in ldap_name_groups):
                group = Group.objects.get(name=check_group)
                group.user_set.remove(user)
                user_Membership_deleted += 1
        if ((user_Membership_deleted > 0) or (user_Membership_added > 0)):
            group.save()
            logger.info("Group membership for user %s synchronized: %d Added, %d Removed" % (user.username, user_Membership_added, user_Membership_deleted))
        self.stats_membership_total += user_Membership_total
        self.stats_membership_added += user_Membership_added
        self.stats_membership_deleted += user_Membership_deleted
        self.stats_membership_errors += user_Membership_errors