简体   繁体   English

覆盖 Django Admin 的保存方法

[英]Override save method of Django Admin

Well, I want to save any instance of a model without taking care about DDBB structure.好吧,我想在不关心 DDBB 结构的情况下保存模型的任何实例。 So I decide to override def save in every model´s class.所以我决定在每个模型的类中覆盖def save Kind of:有点儿:

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.我想我必须重写save的核心代码,但是我检查了它,但没有找到检查插入数据库条件的部分。 Maybe, The problem is only in the validation of the form.也许,问题仅在于表单的验证。

How can I override a specific form in Django Admin?如何覆盖 Django Admin 中的特定表单? Specifically, that one where I add, Delete or Edit one class of the model.具体来说,我在其中添加、删除或编辑一类模型。

You can overwrite save_model of ModelAdmin .您可以覆盖save_modelModelAdmin

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

Well, I want to save any instance of a model without taking care about DDBB structure.好吧,我想在不关心 DDBB 结构的情况下保存模型的任何实例。 So I decide to override def save in every model´s class.所以我决定在每个模型的类中覆盖def save Kind of:有点儿:

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.我想我必须覆盖save的核心代码,但我检查了它,但没有找到检查插入数据库的条件的部分。 Maybe, The problem is only in the validation of the form.也许,问题仅在于表单的验证。

How can I override a specific form in Django Admin?如何覆盖 Django Admin 中的特定表单? Specifically, that one where I add, Delete or Edit one class of the model.具体来说,我添加、删除或编辑模型的一类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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