def add_bidirectional_m2m(form_cls):

    class BidirectionalM2MForm(form_cls):

        def _get_bidirectional_m2m_fields(self):
            try:
                return super(BidirectionalM2MForm, self)._get_bidirectional_m2m_fields()
            except __HOLE__:
                return []

        def __init__(self, *args, **kwargs):
            super(BidirectionalM2MForm, self).__init__(*args, **kwargs)
            if self.instance.pk is not None:
                for m2m_field, related_manager in self._get_bidirectional_m2m_fields():
                    self.fields[m2m_field].initial = getattr(
                        self.instance, related_manager).all()

        def save(self, commit=True):
            """
            Saves this ``form``'s cleaned_data into model instance
            ``self.instance``.

            If commit=True, then the changes to ``instance`` will be saved to the
            database.  If ``instance`` is a new object then it will get saved to
            the database even if commit=False

            Returns ``instance``.
            """
            instance = super(BidirectionalM2MForm, self).save(commit=False)
            force_save = self.instance.pk is None
            if force_save:
                instance.save()
            for m2m_field, related_manager in self._get_bidirectional_m2m_fields():
                setattr(self.instance, related_manager, self.cleaned_data[m2m_field])
            if commit:
                if not force_save:
                    instance.save()
                self.save_m2m()
            return instance

    return BidirectionalM2MForm
dataset/ETHPy150Open kux/django-admin-extend/admin_extend/extend.py/add_bidirectional_m2m