+的'不支持的操作数类型:'type'和'tuple'

时间:2013-12-16 17:26:40

标签: python django

新手在这里。我copy这个python配方,但是当我尝试在我的django上运行时出错了

def get_noconflict_metaclass(bases, left_metas, right_metas):
    """Not intended to be used outside of this module, unless you know
    what you are doing."""
    # make tuple of needed metaclasses in specified priority order
    metas = left_metas + tuple(map(type, bases)) + right_metas
    needed_metas = remove_redundant(metas)

错误

以下是值:

left_metas (<class 'ccad.admin.ModelAdminWithForeignKeyLinksMetaclass'>,)
right_metas ()
...
 File "/opt/myenv/myproject/ccad/admin.py", line 201, in 
class SOAdetailAdmin(admin.ModelAdmin):
 File "/opt/myenv/myproject/ccad/noconflict.py", line 52, in make_class
def make_class(name, bases, adict):
 File "/opt/myenv/myproject/ccad/noconflict.py", line 30, in get_noconflict_metaclass
metas = left_metas + tuple(map(type(), bases,),) + right_metas
TypeError: Error when calling the metaclass bases
unsupported operand type(s) for +: 'type' and 'tuple'

我找不到问题。

输入参数

'''
I'm using this snippet to show Foreign keys in django admin list display
'''
class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass):

def __getattr__(cls, name):

    def foreign_key_link(instance, field):
        target = getattr(instance, field)
        return u'<a href="../../%s/%s/%d">%s</a>' % (
            target._meta.app_label, target._meta.module_name, target.id, unicode(target))

    if name[:8] == 'link_to_':
        method = partial(foreign_key_link, field=name[8:])
        method.__name__ = name[8:]
        method.allow_tags = True
        setattr(cls, name, method)
        return getattr(cls, name)
    raise AttributeError
##############################################

我试图在我的admin.py

中使用它
from noconflict import classmaker
class SOAdetailAdmin(admin.ModelAdmin):
    __metaclass__ = classmaker(ModelAdminWithForeignKeyLinksMetaclass)

1 个答案:

答案 0 :(得分:0)

感谢您的所有评论。它真的有助于指出我该怎么做。

从片段作者说明和示例:

这里的问题是,由于D继承自A,其元类必须从M_A继承而不能是M_B。

classmaker通过自动从M_A和M_B继承来解决问题:

>>> class D(A):
...     __metaclass__=classmaker(right_metas=(M_B,))
>>> type(D)

我将原始代码更改为此,django工作正常:

class SOAdetailAdmin(admin.ModelAdmin):
    __metaclass__ = classmaker(right_metas=(ModelAdminWithForeignKeyLinksMetaclass,))