Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have currently a boolean field called is_active on a model. Whenever I set this field manually in the Django admin to True (initially it it's false) I want it to do a certain action. How can I trigger this field in Django to do this certain action when it is set to True?

I heard about a save_model() method but i don't know how it works.

class Company(models.Model):
    name = models.CharField(max_length=100, unique=True)
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.name
like image 295
Reda Avatar asked Sep 06 '25 20:09

Reda


1 Answers

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)
like image 158
Willem Van Onsem Avatar answered Sep 08 '25 11:09

Willem Van Onsem