Casbin Django ORM Adapter
raw JSON → 1.7.0 verified Fri May 01 auth: no python
Django ORM adapter for PyCasbin, enabling Casbin permission management to store policies in Django models. Version 1.7.0 supports Python >=3.7 and Django 2.2+.
pip install casbin-django-orm-adapter Common errors
error django.core.exceptions.ImproperlyConfigured: Requested setting ..., but settings are not configured. ↓
cause Trying to import adapter before calling django.setup() or without DJANGO_SETTINGS_MODULE set.
fix
Set os.environ['DJANGO_SETTINGS_MODULE'] = 'your_project.settings' and call django.setup() before importing Adapter.
error OperationalError: no such table: casbin_django_orm_adapter_casbinrule ↓
cause Migrations for the casbin_django_orm_adapter app have not been applied.
fix
Add 'casbin_django_orm_adapter' to INSTALLED_APPS in settings.py and run 'python manage.py migrate casbin_django_orm_adapter'.
Warnings
breaking In version 1.5.0, the Adapter initialization changed. adapter = Adapter() now requires model_conf to be passed to the Enforcer, not to the Adapter. ↓
fix Update to use Adapter() without arguments and pass model path to Enforcer.
gotcha The adapter uses Django's ORM, so you must run migrations to create the casbin_rule table before using the adapter. Missing migration leads to table not found errors. ↓
fix Run 'python manage.py migrate casbin_django_orm_adapter' after adding the app to INSTALLED_APPS.
deprecated In version 1.6.0, the Adapter no longer accepts 'model' argument in its constructor; it must be initialized empty. ↓
fix Use adapter = Adapter() (no arguments).
Imports
- Adapter wrong
from casbin_django_orm_adapter import Adaptercorrectfrom casbin_django_orm_adapter.adapter import Adapter - CasbinRule wrong
from casbin_django_orm_adapter import CasbinRulecorrectfrom casbin_django_orm_adapter.models import CasbinRule
Quickstart
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
django.setup()
import casbin
from casbin_django_orm_adapter.adapter import Adapter
adapter = Adapter()
e = casbin.Enforcer('path/to/model.conf', adapter)
# Check permission
sub = 'alice'
obj = 'data1'
act = 'read'
if e.enforce(sub, obj, act):
print('Access granted')
else:
print('Access denied')