Python 覆盖 Django Admin 的保存方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36443245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:53:04  来源:igfitidea点击:

Override save method of Django Admin

pythondjangodjango-admin

提问by Elias MP

Well, I want to save any instance of a model without taking care about DDBB structure. So I decide to override def savein every model′s class. Kind of:

好吧,我想在不关心 DDBB 结构的情况下保存模型的任何实例。所以我决定def save在每个模型的类中覆盖。的种类:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    if condition:
        raise Exception("You can′t insert that element")
    return super(name_class, self).save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)

Well, with this I achieve to insert not raising an exception, but if the instance passes this check I want to insert in the DB whatever primary restriction exists...

好吧,通过这个我实现了插入而不引发异常,但是如果实例通过了这个检查,我想在数据库中插入任何存在的主要限制......

How can I get it?

我怎么才能得到它?

I suppose I must have to override the core code of save, but I checked it and I didn't find the part where I check the conditions for inserting in the DB. Maybe, The problem is only in the validation of the form.

我想我必须覆盖 的核心代码save,但我检查了它,但没有找到检查插入数据库的条件的部分。也许,问题仅在于表单的验证。

How can I override a specific form in Django Admin? Specifically, that one where I add, Delete or Edit one class of the model.

如何覆盖 Django Admin 中的特定表单?具体来说,我添加、删除或编辑模型的一类。

回答by S?n Lam

You can overwrite save_modelof ModelAdmin.

您可以覆盖ModelAdmin的 save_model。

  class MyAdminView(admin.ModelAdmin):
       def save_model(self, request, obj, form, change):
           super(MyAdminView, self).save_model(request, obj, form, change)

回答by Sayse

You shouldn't be doing any kind of validation at all in the save method, models have a cleanmethod so any validation you wish to do should be done in that instead

您根本不应该在 save 方法中进行任何类型的验证,模型有一个干净的方法,因此您希望进行的任何验证都应该在该方法中完成

For more information, see validating objects

有关更多信息,请参阅验证对象