Django-REST User Level Permissions and Object Level Permissions

Reading Time : ~ .

Let us cosider the scenario  of Authors, Books, Readers.

Authors are only allowed to write the books

Readers are only allowed to read the Books.

models.py

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
 
class User(AbstractBaseUser, PermissionsMixin):
    USER_TYPES = (
       ("Author", "Author"),
       ("Reader", "Reader"),
       ("Publisher", "Publisher")
    )
    username = models.CharField(max_length=100, unique=True)
    first_name = models.CharField(_("first name"), max_length=30, blank=True, null=True)
    last_name = models.CharField(_("last name"), max_length=30, blank=True, null=True)
    email = models.EmailField(_("email address"), unique=True)
    is_staff = models.BooleanField(_("staff status"), default=False)
    is_active = models.BooleanField(_("active status"), default=True)
    user_type = models.CharField(choices=USER_TYPES)
    
    def __str__(self):
       return self.email

class Book(models.Model):
    READ_OPTIONS = (
    	('YES', 'YES'),
    	('NO', 'NO')
    )
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    is_allowed_to_read = models.CharField(choices=READ_OPTIONS)

    def __str__(self):
    	return self.name



permissions.py

from rest_framework.permissions import BasePermission

class IsAllowedToWrite(BasePermission):
    
    def has_permission(self, request, view):
        return request.user.user_type == "Author"


class IsAllowedToRead(BasePermission):
    
    def has_object_permission(self, request, view, obj):
        return obj.is_allowed_to_read == "YES"


views.py

from rest_framework import generics
from app.permissions import IsAllowedToWrite, IsAllowedToRead
from app.serializers import WriteBookSerializer, 


class WriteBookView(generics.CreateAPIView):
	
    serializer_class = WriteBookSerializer
    permission_classes = (IsAllowedToWrite,)


class ReadBookView(generics.RetrieveAPIView):
	
    serializer_class = ReadBookSerializer
    permission_classes = (IsAllowedToWrite,) 

 

for more details visit rest-framework documentaion or source code github 
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Django Custom Management Command Siva Chittamuru

In Django project, We could manage by executing some commands which could be invoked through the manage.py.

For example:
# Sync database
python manage.py syncdb

...

Continue Reading...
How to customize Django Oscar Models, Views and URL's Chaitanya Kattineni

In order to customize models, views and urls, you need to fork an Oscar core app in which model/view resides. Then you should be able ...

Continue Reading...
Extract data from PDF and all Microsoft Office files in python Ashwin Kumar

The quick way to get/extract text from PDFs in Python is with the Python library "slate". Slate is a Python package that simplifies the process ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties