Search code examples
pythondjangoadmin

How to check initial data when save model in ModelAdmin?


I use save_model() method in ModelAdmin.

I want to do sth when specific field changed (i.e. staus). So I want to know initial data before save admin so I could check it in save_model.

I knew that there's __init__ and __save__ method in Model itself, but I want to activate code only in ModelAdmin.

Here's sample code below

def save_model(self, request, obj, form, change):
    if obj.status != xxx (intial data?) and obj.status == 7:
        # do sth
    super(CustomAdmin, self).save_model(request, obj, form, change)

Summary

  • Can I know initial data from obj after save in admin?
  • Is there any way to do sth when only saving in admin site?

Thanks in advance.


Solution

  • Finally I found a solution!

    I can know all changed data by form.changed_data, so I can do sth when specific field is in form.changed_data.

    like this

    def save_model(self, request, obj, form, change):
        if 'status' in form.changed_data:
            if obj.status != xxx (intial data?) and obj.status == 7:
            # do sth
        super(CustomAdmin, self).save_model(request, obj, form, change)
    

    I hope it will help somebody!