Use Object Permissions

Let’s learn by example.

We’ll use object permissions to grant different users and groups access to different Blog objects. We’ll assume that we can find the Blog model in blog.models.Blog.

Manage Object Permissions

We can add, modify and delete object permissions via Django’s admin interface.

Before we can add an object permission to Blog objects, we have to register permission types for the model. We’ll add a read and a write permission for the Blog model:

_images/add_permission_type_admin.png

Now we want to give the user John the permission to read the blog News. We have to create an object permission object. Therefor, we select the object we want to create the permission for (in our case a Blog object) and use the admin action Create Object Permission for a user.

_images/add_user_permission_action.png

Then we have to select the newly generated object permission object and add a user and permissions:

_images/modify_object_permission.png

We can add group permissions the same way (use Create Object Permission for group and Group Object Permission instead)

Checking permissions

There are two ways to check object permissions:
  • user.has_perm(‘foo’, bar)
    >>> blog = Blog.objects.get(name='News')
    >>> user = User.objects.get(username='John')
    >>> if user.has_perm('read', blog):
    >>>     # display blog
    
  • obj_permission_required decorator

Before we can use the decorator, we have to declare a function, that returns the object we want to check permissions for The decorator will pass the object to the view if the user has the permission.

from django.http import Http404
from blog.models import Blog
from object_permission_backend_nonrel.decorators import obj_permission_required

def get_blog_object(request, *args, **kwargs):
    try:
        blog = Blog.objects.get(url=request.path)
    except Blog.DoesNotExist:
        raise Http404('Requested Travel Blog not found')

@obj_permission_required('view', get_blog_object)
def display_blog(request, obj=None):
    blog = obj
    # display blog object