Django admin:覆盖删除方法 [英] Django admin: override delete method

查看:559
本文介绍了Django admin:覆盖删除方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的admin.py如下:

I have admin.py as follows:

  class profilesAdmin(admin.ModelAdmin):
     list_display = ["type","username","domain_name"]

现在我想在删除之前执行一些操作对象:

Now i want to perform some action before deleting the object:

  class profilesAdmin(admin.ModelAdmin):
     list_display = ["type","username","domain_name"]

     @receiver(pre_delete, sender=profile)
     def _profile_delete(sender, instance, **kwargs):
        filename=object.profile_name+".xml"
        os.remove(os.path.join(object.type,filename))

如果我使用这种删除信号方法,则会收到一条错误消息,提示 self 应该是第一个参数。

If i use delete signal method like this I get an error saying self should be the first parameter.

如何我修改了上面的函数吗?

而且我想检索要删除的对象的profile_name。怎么做?

How can I modify the above function?
And I want to retrieve the profile_name of the object being deleted. How can this be done?

我还尝试覆盖delete_model方法:

I also tried overriding delete_model method:

def delete_model(self, request, object):
    filename=object.profile_name+".xml"
    os.remove(os.path.join(object.type,filename))
    object.delete()

但是如果必须一次删除多个对象,则此方法无效。

But this dosn't work if multiple objects have to be deleted at one shot.

推荐答案

您的 delete_model 方法在正确的轨道上。 django管理员一次对多个对象执行操作时,它使用更新功能。但是,正如您在文档中看到的那样,这些操作仅在数据库级别使用SQL执行。

You're on the right track with your delete_model method. When the django admin performs an action on multiple objects at once it uses the update function. However, as you see in the docs these actions are performed at the database level only using SQL.

您需要添加 delete_model 方法作为自定义操作 django管理员。

You need to add your delete_model method in as a custom action in the django admin.

def delete_model(modeladmin, request, queryset):
    for obj in queryset:
        filename=obj.profile_name+".xml"
        os.remove(os.path.join(obj.type,filename))
        obj.delete()

然后将您的函数添加到您的modeladmin-

Then add your function to your modeladmin -

class profilesAdmin(admin.ModelAdmin):
    list_display = ["type","username","domain_name"]
    actions = [delete_model]

这篇关于Django admin:覆盖删除方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆