0

If a user is de-activated I want all memberships deleted. I thought this code in models.py would do it. But is doesn't, the relation is still there.


class User(AbstractUser):
    membership_type = ManyToManyField(MembershipType, blank=True)

....

def __init__(self, *args, **kwargs):
    super(User, self).__init__(*args, **kwargs)
    self.old_is_active = self.is_active


def save(self, **kwargs):
    # Membership is cancelled
    if self.old_is_active is True and self.is_active is False:
        self.membership_type.clear()            
    super(User, self).save()

I also changed it and debugged it like this.

@receiver(post_save, sender=User)
def clear_membership(sender, instance, **kwargs):
    if instance.old_is_active is True and instance.is_active is False:
        print('clearing post_save')
        print(instance.membership_type.all())
        instance.membership_type.clear()
        print(instance.membership_type.all())

It prints out the relation. And after the clear() the relations are gone. But when I look in my Admin GUI, the relation is still there ...?

A. Nurb
  • 496
  • 1
  • 3
  • 17
  • Can you try making sure that the `.clear()` line is executed via debugger or a `print` statement? If it is, try opening a shell and running `whichever_user.membership_type.clear()` and seeing if that clears the relationship. – schillingt Feb 27 '20 at 16:33
  • I checked with a ```print``` statement and it gets executed. I checked in the shell, and it clears the relationship. Could it be, that it is before the ```save()``` – A. Nurb Feb 27 '20 at 16:42
  • That seems possible. – schillingt Feb 27 '20 at 17:23
  • I added a new version to the original question. Do you have any more ideas how to tackle this? – A. Nurb Feb 27 '20 at 19:54
  • Are you adding an instance somewhere else automatically? You can check the ids on the items being deleted in the database and compare it with those after they exist again. – schillingt Feb 27 '20 at 20:03
  • I now used the ```on_transaction_commit``` function describe here: https://stackoverflow.com/questions/23795811/django-accessing-manytomany-fields-from-post-save-signal And that works! – A. Nurb Feb 27 '20 at 20:19

0 Answers0