Skip to content

Instantly share code, notes, and snippets.

@plar
Created March 6, 2015 20:14
Show Gist options
  • Save plar/5acaf6467e327dd3e478 to your computer and use it in GitHub Desktop.
Save plar/5acaf6467e327dd3e478 to your computer and use it in GitHub Desktop.
Custom global permissions for Django v1.7.x without model
"""
Registers any number of application permissions without model
Examples:
# .../project/app/models.py
from django.apps import apps
register_application_permissions(
(
('can_reboot_server', 'Can Reboot Server',),
),
apps.get_app_config('app_name'))
# .../project/app/views.py
if not request.user.has_perm('app.can_reboot_server'):
return HttpResonseRedirect(login_url)
To synchronize all permissions with database run the following:
# ./manage.py migrate
"""
def register_application_permissions(permissions, sender):
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models import signals
def _sync_permissions(permissions, app, verbosity):
if verbosity >= 2:
print "Synchronize '%s' application permissions" % app.label
# create content type
content_type, created = ContentType.objects.get_or_create(model='',
app_label=app.label,
defaults={'name': app.label})
if created and verbosity >= 2:
print "Content type '%s' has been created" % content_type.name
# create permissions
for codename, name in permissions:
perm, created = Permission.objects.get_or_create(codename=codename,
content_type__pk=content_type.id,
defaults={'name': name, 'content_type': content_type})
if created and verbosity >= 2:
print "Permission '%s' has been created" % perm.codename
def _post_migrate_receiver(sender, **kwargs):
_sync_permissions(permissions, sender, kwargs.get('verbosity', 0))
signals.post_migrate.connect(_post_migrate_receiver, sender=sender, weak=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment