Skip to content

Instantly share code, notes, and snippets.

@devsnd
Forked from magopian/fix_permissions.py
Last active August 29, 2015 14:06
Show Gist options
  • Save devsnd/4a898c349880aca315d0 to your computer and use it in GitHub Desktop.
Save devsnd/4a898c349880aca315d0 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
import os
import sys
# based on https://gist.github.com/magopian/7543724
#
# refactored for manual control over permissions created.
projectname = input("Enter project name (for settings import): ")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", projectname+".settings")
"""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 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.db.models import get_models
def main():
for model in get_models():
model_meta = model._meta
content_type = None
content_type_model = model_meta.object_name.lower()
content_type_name = model_meta.verbose_name_raw
try:
content_type = ContentType.objects.get(
app_label=model_meta.app_label,
model=model_meta.object_name.lower(),
)
except ContentType.DoesNotExist:
question = "ContentType %s | %s does not exist. Create? (y/n)" % (model_meta.app_label, content_type_model)
create_ct = input(question) == 'y'
if create_ct:
content_type = ContentType(
app_label=model_meta.app_label,
model=content_type_model,
name=content_type_name)
content_type.save()
print('Created Content Type "%s"' % content_type)
if content_type:
for permission in missing_permissions(model_meta, content_type, content_type_name):
create_permission = input("Missing permission %s, create? (y/n)" % permission) == 'y'
if create_permission:
permission.save()
print('Created permission "%s"' % permission)
def missing_permissions(model_meta, content_type, content_type_name):
for codename, name in _get_all_permissions(model_meta, content_type):
try:
permission = Permission.objects.get(
codename=codename,
content_type=content_type,
)
except Permission.DoesNotExist:
yield Permission(
codename=codename,
content_type=content_type,
name=content_type_name)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment