简体   繁体   中英

Override (save_model) in django admin for All models/apps in projects

How could I implement override save method for all models in all Apps inside Admin panel?

def save_model(self, request, obj, form, change):
    
    pass

I can implement it in one or two models "inherit and adding it in register method", but I really need it to execute whenever admin clicks save in Admin panel and implement some code before save.

In my team we already overridden ModelAdmin class. Answer depends on your project.

In examples i use old python super() sintaxis, it helps to debug the code.

Easy way with class. Create somewhere in project

from django.contrib.admin import ModelAdmin:

Class ModelAmin(ModelAdmin):
    def save_model(self, *args, **kwargs):
        # do some staff before
        super(ModelAdmin, self).save_model(*args, **kwargs)
        # do some staff after

Everywhere in project made find from django.contrib.admin import ModelAdmin replace to from module.with.myModelAdmin import ModelAdmin .

All next ModelAdmins you should build with your ModelAdmin .

Second way with ModelAdminMixin . Code is fast the same. Somethere put mixin:

Class ModelAminMixin:
    def save_model(self, *args, **kwargs):
        # do some staff before
        super(ModelAdminMixin, self).save_model(*args, **kwargs)
        # do some staff after

Everywhere in project made find with regexp class BlaBlaBla(bla, bla, ModelAdmin): and replace to class BlaBlaBla(bla, bla, ModelAdminMixin, ModelAdmin): .

All next ModelAdmins you should build with inheritance from ModelAdminMixin and ModelAdmin . This is a little bit more flexible: you can decide add or not this mixin.

Next Way - MonkeyPatching .

Somethere put your mixin from "second way". Somethere in admin.py:

from django.contrib.admin import ModelAdmin.
from module.with.myModelAdminMixin import ModelAdminMixin

ModelAdmin.__bases__ = (ModelAdminMixin,) + ModelAdmin.__bases__

After that you should not do something else. But it is a wrong way to code. Is "monkey patching" really that bad?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM