Skip to content

Instantly share code, notes, and snippets.

@xleon
Forked from magopian/fix_permissions.py
Last active January 31, 2018 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xleon/fa1741ca3f0b063c5e654744b33e6606 to your computer and use it in GitHub Desktop.
Save xleon/fa1741ca3f0b063c5e654744b33e6606 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
# -*- 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.
"""
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.apps import apps
class Command(BaseCommand):
help = "Fix permissions for proxy models."
def handle(self, *args, **options):
for model in apps.get_models():
opts = model._meta
sys.stdout.write('{}-{}\n'.format(opts.app_label, opts.object_name.lower()))
ctype, created = ContentType.objects.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower())
for codename, name in _get_all_permissions(opts):
sys.stdout.write(' --{}\n'.format(codename))
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))
@rscbugtrack
Copy link

rscbugtrack commented Jan 31, 2018

Hello xleon,
i need help that how to use this code....
Django= 1.11.6
python = 3.5

Thanks in advance ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment