|
1 """ |
|
2 Creates permissions for all installed apps that need permissions. |
|
3 """ |
|
4 |
|
5 from django.db.models import get_models, signals |
|
6 from django.contrib.auth import models as auth_app |
|
7 |
|
8 def _get_permission_codename(action, opts): |
|
9 return u'%s_%s' % (action, opts.object_name.lower()) |
|
10 |
|
11 def _get_all_permissions(opts): |
|
12 "Returns (codename, name) for all permissions in the given opts." |
|
13 perms = [] |
|
14 for action in ('add', 'change', 'delete'): |
|
15 perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw))) |
|
16 return perms + list(opts.permissions) |
|
17 |
|
18 def create_permissions(app, created_models, verbosity, **kwargs): |
|
19 from django.contrib.contenttypes.models import ContentType |
|
20 from django.contrib.auth.models import Permission |
|
21 app_models = get_models(app) |
|
22 if not app_models: |
|
23 return |
|
24 for klass in app_models: |
|
25 ctype = ContentType.objects.get_for_model(klass) |
|
26 for codename, name in _get_all_permissions(klass._meta): |
|
27 p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id, |
|
28 defaults={'name': name, 'content_type': ctype}) |
|
29 if created and verbosity >= 2: |
|
30 print "Adding permission '%s'" % p |
|
31 |
|
32 def create_superuser(app, created_models, verbosity, **kwargs): |
|
33 from django.contrib.auth.models import User |
|
34 from django.core.management import call_command |
|
35 if User in created_models and kwargs.get('interactive', True): |
|
36 msg = "\nYou just installed Django's auth system, which means you don't have " \ |
|
37 "any superusers defined.\nWould you like to create one now? (yes/no): " |
|
38 confirm = raw_input(msg) |
|
39 while 1: |
|
40 if confirm not in ('yes', 'no'): |
|
41 confirm = raw_input('Please enter either "yes" or "no": ') |
|
42 continue |
|
43 if confirm == 'yes': |
|
44 call_command("createsuperuser", interactive=True) |
|
45 break |
|
46 |
|
47 signals.post_syncdb.connect(create_permissions, |
|
48 dispatch_uid = "django.contrib.auth.management.create_permissions") |
|
49 signals.post_syncdb.connect(create_superuser, |
|
50 sender=auth_app, dispatch_uid = "django.contrib.auth.management.create_superuser") |