Django Admin - additional actions after creating an object

How to perform additional actions just after the new object is created using Django Admin ?

So every time a new object is created (when I click Save button in Django Admin), I need to do some calculations, update some other models, etc…

How can I do that ?

There is no separate “create” hook vs “update”. You can try overriding your model’s save method and seeing if you can tell if this is a new instance or not.

In the general case, you can’t be 100% sure. But if you’re only working with code and models that you have written, you may be able to rely upon the idea that before the model is actually inserted the first time, the pk field evaluates to False.

So what I would try would be a custom save method that:

  • before calling super().save(…), checked to see if the pk field evaluates to False
    • if so, set a flag indicating a new row is being created
  • call super().save(…) to save the row
  • Check the flag previously set, if it’s true, then execute your post-insert code.

Another way that may work for you is to rely upon the idea that it’s better to ask forgiveness than permission. Do your save, then update the other fields anyway - or at least see if you can determine whether or not those fields need to be updated.

Ken

You could use the django signals post save to handle the calculations and other stuff.

1 Like

A Much better answer - I missed seeing the created argument when I looked at that yesterday and didn’t think you got that information. Great catch!

1 Like