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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With