rsinger86/django-lifecycle

has_changed function not works when create with before_save

Closed this issue · 3 comments

@hook('before_save', when='password', has_changed=True)
def set_hashed_password(self):
    self.set_password(self.password)

When a user is created, It doesn't work
I think It needs to work

This is interesting. Personally, I don't think of an object as having a previous value if it is coming into existence for the first time. I guess this should depend on how similar projects handle this - would want to be consistent with users' expectations.

As an alternative in the meantime, you could stack an before_create decorator:

@hook('before_create')
@hook('before_update', when='password', has_changed=True)
def set_hashed_password(self):
    self.set_password(self.password)

I changed "before_save" to "before_update" to make things more distinct, though this isn't necessary.

Thank you answer! I think If you get this idea from Rails, many people can make a mistake.

Good point, and I appreciate you raising this. I'll take a closer look at Rails callbacks and at the very least I think this needs to be clarified in the documentation.