django-extensions/django-extensions — pull request #565 by alexhayes (2014-09-29 22:20:55+00:00)
Title: Add custom permissions using `update_permissions` command

I wanted a nice way to hook into update_permissions so that when it was run I could also add 'view' and 'list' permissions to all content types. My solution was to create a signal that is sent upon beginning and end of `update_permissions`.

The reason I called the signals `pre_command` and `post_command` was because I thought they could then be rolled out for other commands.

If anyone is interested, the code that creates the permissions is as follows;

```python
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django_extensions.management.signals import post_command
from django_extensions.management.commands.update_permissions import Command

def add_permissions(sender, **kwargs):
"""
Add view and list permissions to all content types.
"""
# for each of our content types
for content_type in ContentType.objects.all():

for action in ['view', 'list']:
# build our permission slug
codename = "%s_%s" % (action, content_type.model)

# if it doesn't exist..
if not Permission.objects.filter(content_type=content_type, codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can %s %s" % (action, content_type.name))
print "Added %s permission for %s" % (action, content_type.name)
post_command.connect(add_permissions, Command)
```