Deleting a user when deleting UserProfile

I created UserProfile(extends from the user) and recorded onsettings.py

 AUTH_PROFILE_MODULE = 'mainapp.UserProfile'.

When I delete UserProfile(from the administration area), I also delete the item User.

I am trying to delete a user like this self.user.delete(), but the delete method (in UserProfile) does not call. Why?

This is my code:

class UserProfile(models.Model):
    avatar = models.ImageField(upload_to = settings.PATH_AVATARS, blank=True)
    url = models.URLField(blank=True)
    user = models.OneToOneField(User)

    def __unicode__(self):
        return self.user.username

    def delete(self, *args, **kwargs):
        self.user.delete()
        super(UserProfile, self).delete(*args, **kwargs)
+5
source share
1 answer

First, to answer why "delete ()" is not called from the administrator. This statement:

  • The truth is if objects are removed from the list view , i.e. / admin / auth / user / check some fields, then click Actions → delete), this is because the delete () queryset method is called ,
  • change_form, ../admin/auth/user/1/ , delete()

, _ . :

from django.db.models import signals

def delete_user(sender, instance=None, **kwargs):
    try:
        instance.user
    except User.DoesNotExist:
        pass
    else:
        instance.user.delete()
signals.post_delete.connect(delete_user, sender=UserProfile)

:

In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()

In [2]: user=User(username='foo'); user.save()

In [3]: profile=UserProfile(user=user); profile.save()

In [4]: UserProfile.objects.all().delete()

In [5]: User.objects.all()
Out[5]: []

, , delete() :

In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()

In [2]: user=User(username='foo'); user.save()

In [3]: profile=UserProfile(user=user); profile.save()

In [4]: profile.delete()

In [5]: User.objects.all()
Out[5]: []

, - :

In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()

In [2]: user=User(username='foo'); user.save()

In [3]: profile=UserProfile(user=user); profile.save()

In [4]: user.delete()

In [5]: User.objects.all()
Out[5]: []

In [6]: UserProfile.objects.all()
Out[6]: []

, Django.

+11

All Articles