1

我使用 django-guardian 获取对象级权限。如何将其集成到自己的代码中的文档很好: http ://packages.python.org/django-guardian/userguide/admin-integration.html

但是我怎样才能将它添加到其他应用程序的模型中呢?我不想修改例如django.contrib.auth 的代码。

4

1 回答 1

1

我在 django-reversion 的源代码中找到了解决方案。有一个助手叫做patch_admin(). 这是为 django-guardian 修改的代码片段。

# Copy of django-reversion helpers.py
def patch_admin(model, admin_site=None):
    """
    Enables version control with full admin integration for a model that has
    already been registered with the django admin site.

    This is excellent for adding version control to existing Django contrib
    applications. 
    """
    admin_site = admin_site or admin.site
    try:
        ModelAdmin = admin_site._registry[model].__class__
    except KeyError:
        raise NotRegistered, "The model %r has not been registered with the admin site." % model
    # Unregister existing admin class.
    admin_site.unregister(model)
    # Register patched admin class.
    class PatchedModelAdmin(GuardedModelAdmin, VersionAdmin, ModelAdmin): # Remove VersionAdmin, if you don't use reversion.
        pass
    admin_site.register(model, PatchedModelAdmin)

from django.contrib.auth.models import Group
patch_admin(Group)
于 2012-04-19T14:09:44.693 回答