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