[Django]-How to do something when I change a field in Django admin for a model?

9👍

You can indeed override the save_model(..) method [Django-doc] in the ModelAdmin. The form parameter contains the Form in the model admin, and you can inspect the .changed_data [Django-doc] to inspect if the value changed:

from app.models import Company
from django.contrib import admin

class CompanyAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        field = 'is_active'
        super().save_model(request, obj, form, change)
        if change and field in form.changed_data and form.cleaned_data.get(field):
            # ... do a certain action
            pass

admin.site.register(Company, CompanyAdmin)

Leave a comment