call a method in Django admin site

2019-09-02 13:51发布

问题:

i have a Django project and right now everything works fine. i have a Django admin site and now, i want that when i add a new record to my model, a function calls simultaneously and a process starts. how i can do this? what is this actions name?

回答1:

  • 1 WAY

You can go to your models.py into your app by using django signal you can do this.

from django.db.models.signals import post_save

class Test(models.Model):
    # ... fields here

# method for updating
def update_on_test(sender, instance, **kwargs):
     # custome operation as you want to perform

# register the signal
post_save.connect(update_on_test, sender=Test)
  • 2 WAY

You can ovveride save() method of modeladmin class if you are filling data into table by using django admin.

class TestAdmin( admin.ModelAdmin ):
    fields  = ['title', 'body' ]
    form = TestForm

    def save_model(self, request, obj, form, change):
         # your login if you want to perform some comutation on save 
         # it will help you if you need request into your work
         obj.save()