Django管理员:使用类进行批量管理操作 [英] Django Admin: making bulk admin actions with a class

查看:93
本文介绍了Django管理员:使用类进行批量管理操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在Django中自动创建一系列管理操作。

I've been trying to automate the creation of a series of admin actions in Django.

基本上,我想创建批量更改状态字段的可能性一个Project对象。状态字段是ForeignkeyField。

Basically I want to create the possibility to bulk change a status field on a Project object. The status field is a ForeignkeyField.

我以为这样做的类可以工作:

I thought making a Class like this would work:

class StatusAction(object):

    def __init__(self,status):
         self.status = status

    def make_action(self, modeladmin, request, queryset):
        self.queryset = queryset.update(status=self.status)

    make_action.short_description = "Change status to '%s' for selected projects" % status

然后声明如下操作:

actions = [StatusAction(s.id).make_action for s in Status.objects.all()]

我遇到两个问题:


  • 只有一个操作在Admin界面最后一个declerated)。

  • make_action.short_description属性具有类范围,因此我无法使其具体针对每个实例。将self.make_action.short_description放在make_action中也不起作用。

我也试着用一个闭包(函数在函数中) )。它解决了一个功能问题的属性,但在管理员中仍然只有一个动作。

I also tried doing this with a closure (function in a function). It solves the attribute of a function problem, but still only one action ends up in the admin.

推荐答案

据了解,函数应该有不同的名称:

As I understand the action functions should have different names:

def create_action(status):
    def action_func(modeladmin, request, queryset):
        print status
    action_func.__name__ = 'make_action_%d' % status.id
    action_func.short_description = "Change status to '%s' for selected projects" % status
    return action_func

actions = []
for s in Status.objects.all():
    actions.append(create_action(s))

这篇关于Django管理员:使用类进行批量管理操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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