Skip to content

Instantly share code, notes, and snippets.

@nicpottier
Created March 22, 2011 07:43
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nicpottier/880901 to your computer and use it in GitHub Desktop.
Save nicpottier/880901 to your computer and use it in GitHub Desktop.
Adds a view permission to all your models in Django
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# for each of our content types
for content_type in ContentType.objects.all():
# build our permission slug
codename = "view_%s" % content_type.model
# if it doesn't exist..
if not Permission.objects.filter(codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can view %s" % content_type.name)
print "Added view permission for %s" % content_type.name
# check for all our view permissions after a syncdb
post_syncdb.connect(add_view_permissions)
@antte
Copy link

antte commented Jan 12, 2012

Thanks a bunch for this!

For further help:
https://docs.djangoproject.com/en/dev/ref/signals/#post-syncdb
"Any handlers that listen to this signal need to be written in a particular place: a management module in one of your INSTALLED_APPS."

So just include a normal python module in one of your apps called "management" (remember python modules are folders that have an init.py file in them). And include this code there, worked out of the box.

@nyaruka
Copy link

nyaruka commented Jan 12, 2012

One gotcha that we came across is that this starts getting pretty slow, especially in unit tests.

We added some tricks in Smartmin (which includes this functionality) to speed that up by trying to detect whether we have synced the last app, but there are some gotchas in some cases. No perfect solution that I know of.

@antte
Copy link

antte commented Jan 12, 2012

I'll keep a look out for that, thanks

@fstnando
Copy link

Hola a todos, muy bueno!!!, para integrar con el admin se me ocurrio extender el admin. Como ejemplo utilizamos un usuario le damos solo permiso de ver y que sea staff.

Lo probe con la version django 1.6.

Este es un ejemplo de una app, el archivo es "admin.py":

https://gist.github.com/fstnando/11291377

Espero que les sirva.
Saludos

@xangmuve
Copy link

se ve muy bueno voy a probarlo...

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