Skip to content

Instantly share code, notes, and snippets.

@gutierri
Forked from magopian/fix_permissions.py
Last active April 18, 2018 14:58
Show Gist options
  • Save gutierri/970ce5df55475c3f6dc76348f9b98c84 to your computer and use it in GitHub Desktop.
Save gutierri/970ce5df55475c3f6dc76348f9b98c84 to your computer and use it in GitHub Desktop.
Django admin command to "fix permissions" (create them properly for proxy models).This is needed because of the following bug in Django (not fixed as of 1.6): https://code.djangoproject.com/ticket/11154 (Work with Django > 1.6 and <= 1.9.X)
# -*- coding: utf-8 -*-
"""Add permissions for proxy model.
This is needed because of the bug https://code.djangoproject.com/ticket/11154
in Django (as of 1.6, it's not fixed).
When a permission is created for a proxy model, it actually creates if for it's
base model app_label (eg: for "article" instead of "about", for the About proxy
model).
What we need, however, is that the permission be created for the proxy model
itself, in order to have the proper entries displayed in the admin.
"""
from __future__ import unicode_literals, absolute_import, division
import sys
from django.contrib.auth.management import _get_all_permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from django.utils.encoding import smart_unicode
try:
from django.db.models import get_models
models = get_models()
except ImportError:
from django.apps import apps
models = apps.get_models()
class Command(BaseCommand):
help = "Fix permissions for proxy models."
def handle(self, *args, **options):
for model in models:
opts = model._meta
ctype, created = ContentType.objects.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower(),
defaults={'name': smart_unicode(opts.verbose_name_raw)})
for codename, name in _get_all_permissions(opts, ctype):
p, created = Permission.objects.get_or_create(
codename=codename,
content_type=ctype,
defaults={'name': name})
if created:
sys.stdout.write('Adding permission {}\n'.format(p))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment