Add Permission To Django Admin
Solution 1:
Adding 'view' permission to default permissions list
Your solution works, but you should really avoid editing source code if possible. There's a few ways to accomplish this within the framework:
1. Add the permission duringpost_syncdb()
:
In a file under your_app/management/
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
defadd_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""# for each of our content typesfor content_type in ContentType.objects.all():
# build our permission slug
codename = "view_%s" % content_type.model
# if it doesn't exist..ifnot Permission.objects.filter(content_type=content_type, 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)
Whenever you issue a 'syncdb' command, all content types can be checked to see if they have a 'view' permission, and if not, create one.
- SOURCE: The Nyaruka Blog
2. Add the permission to the Meta permissions option:
Under every model you would add something like this to its Meta
options:
classPizza(models.Model):
cheesiness = models.IntegerField()
classMeta:
permissions = (
('view_pizza', 'Can view pizza'),
)
This will accomplish the same as 1 except you have to manually add it to each class.
3. NEW in Django 1.7, Add the permission to the Meta default_permissions option:
In Django 1.7 they added the default_permissions Meta option. Under every model you would add 'view' to the default_permissions option:
classPizza(models.Model):
cheesiness = models.IntegerField()
classMeta:
default_permissions = ('add', 'change', 'delete', 'view')
Test the 'view' permission is added to all models
As for testing the whether a user has the permission, you can test on the has_perm()
function. For example:
user.has_perm('appname.view_pizza') # returns True if user 'Can view pizza'
Post a Comment for "Add Permission To Django Admin"