Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework permission 'isAdminorReadonly'

I want only admin to add content to model but that can be read by anyone. Is there any existing permission class that i can use for the same. Or what will be the best approach without object level permissions.Code for the same is

class TagList(generics.ListCreateAPIView):
    serializer_class = TagSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('title',)
    def get_queryset(self):
        return Tag.objects.all()
like image 490
georoot Avatar asked Jun 22 '16 12:06

georoot


People also ask

What is permission in Django REST framework?

Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.

How do I give permission in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

How do I update user details in Django REST framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.


1 Answers

Let's be specific to your questions.

  1. Is there any existing permission class that i can use for the same?

Ans: No. There is no permission provided by drf (till version 3) to provide full access to admin and readonly to anyone (I believe anonymous as well).

  1. What will be the best approach without object level permissions?

Ans: I would suggest to have a custom view level permission as follows:

from rest_framework.permissions import IsAdminUser, SAFE_METHODS

class IsAdminUserOrReadOnly(IsAdminUser):

    def has_permission(self, request, view):
        is_admin = super(
            IsAdminUserOrReadOnly, 
            self).has_permission(request, view)
        # Python3: is_admin = super().has_permission(request, view)
        return request.method in SAFE_METHODS or is_admin
like image 124
Ansuman Bebarta Avatar answered Oct 05 '22 23:10

Ansuman Bebarta