对于那些仍在寻找的人:
您可以创建一个没有数据库表的辅助模型。该模型可以为您的项目带来您需要的任何权限。无需处理 ContentType 或显式创建 Permission 对象。
from django.db import models
class RightsSupport(models.Model):
class Meta:
managed = False # No database table creation or deletion \
# operations will be performed for this model.
default_permissions = () # disable "add", "change", "delete"
# and "view" default permissions
permissions = (
('customer_rights', 'Global customer rights'),
('vendor_rights', 'Global vendor rights'),
('any_rights', 'Global any rights'),
)
之后manage.py makemigrations
,manage.py migrate
您可以像使用其他任何权限一样使用这些权限。
# Decorator
@permission_required('app.customer_rights')
def my_search_view(request):
…
# Inside a view
def my_search_view(request):
request.user.has_perm('app.customer_rights')
# In a template
# The currently logged-in user’s permissions are stored in the template variable {{ perms }}
{% if perms.app.customer_rights %}
<p>You can do any customer stuff</p>
{% endif %}