Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist?
Primary key attribute usually assigned by the database when the instance saved first time. So you can use something like if instance.pk is None
According to the latest Django documentation, pre_save
does NOT send a created
argument. Post_save
however does. I could not find any reference of the signal sending created
since version 1.0.
I am not sure if this is the recommended way but @Radagast's method didnt work for me(not sure if its because I use custom Pk's).
I tried the following(not sure if this is the best way):
@receiver(pre_save, sender=YourModelName, weak=False, )
def presave_payment_model_check(sender, instance=None, created=False, **kwargs):
#Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate
if instance._state.adding:
# we would need to create the object
print "Creating an object"
else:
#we are updating the object
print "Updating an object"
Reference: Django : What is the role of ModelState?