Django: UserProfile with Unique Foreign Key in Django Admin Django: UserProfile with Unique Foreign Key in Django Admin django django

Django: UserProfile with Unique Foreign Key in Django Admin


It is normal that django will create the admin instance afterwards, as the saving consists always of something like this:

  1. Create User object
  2. Create Profile object (can't be before because it points to a user).

When saving the User object the django ORM cannot know the create profile object will come after it so it will not delay the post_save signal in any way (doesn't even make sense).

The best way to handle this (imho) if you want to keep the post_save signal, is to override the save method of UserExtension to something like this:

def save(self, *args, **kwargs):    try:        existing = UserExtension.objects.get(user=self.user)        self.id = existing.id #force update instead of insert    except UserExtension.DoesNotExist:        pass     models.Model.save(self, *args, **kwargs)

Note that this does force every insert that points to the same user as an existing object to become an update, this can be unexpected behaviour for other parts of code.