Django Admin does not support object-permissions, in the sense that it will never ask for permission to perform an action on an object, only whether a user is allowed to act on (any) instances of a model.
If you'd like to tell Django whether a user has permissions on a specific object, you'd have to override the following methods of a model's ModelAdmin:
has_view_permission(user, obj=None)
has_change_permission(user, obj=None)
has_delete_permission(user, obj=None)
rules comes with a custom ModelAdmin
subclass, rules.contrib.admin.ObjectPermissionsModelAdmin
, that overrides these methods to pass on the edited model instance to the authorization backends, thus enabling permissions per object in the Admin:
from django.contrib import admin
from rules.contrib.admin import ObjectPermissionsModelAdmin
from .models import Book
class BookAdmin(ObjectPermissionsModelAdmin):
pass
admin.site.register(Book, BookAdmin)
Now this allows you to specify permissions like this:
rules.add_perm('books', rules.always_allow)
rules.add_perm('books.add_book', has_author_profile)
rules.add_perm('books.change_book', is_book_author_or_editor)
rules.add_perm('books.delete_book', is_book_author)
To preserve backwards compatibility, Django will ask for either view or change permission. For maximum flexibility, rules behaves subtly different: rules will ask for the change permission if and only if no rule exists for the view permission.
add_book
是添加书籍的权限,而不是“保存”书籍的权限。我认为你应该在表单中处理这个问题(甚至只需“注入”用户),以便他/她根本无法添加其他数据。 - Willem Van OnsemObjectPermissionsModelAdmin
和add_perm
谓词的完整文件吗? 同时请查看 https://github.com/dfunckt/django-rules/blob/v2.0.0/tests/testapp/rules.py 尝试将你的代码与存储库中的代码进行比较。 - Kamil Niski