Custom permissions in django isn't working


I want to add custom permissions:

  1. Only admin and owner of the object can modify the object
  2. All registered users can view the objects

My solution:


class IsApplicationAdmin(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            if request.user.is_superuser or request.user.user_type == "Admin":
                return True
            if request.method in SAFE_METHODS:
                return True

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True

        return obj.user_name == request.user # owner can modify the object

PROBLEM — for PATCH request (partial update) I have this error

    "detail": "You do not have permission to perform this action."

I was debugging the code and see debugging log only in has_permission (no logs in has_object_permission)

What should I fix?

I was reading and the table said that PATH request relates to object permissions


Custom permissions and authentication should be checked in the below manner

from rest_framework import permissions  
from rest_framework.permissions import IsAuthenticated

class IsApplicationAdmin(IsAuthenticated):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS or request.user.is_superuser:
            return True
        return obj.user_name == request.user.username # I think you want to check usernames here because on left side its obj.user_name ?

Please try with this approach and then let me know if there is some issue.

Answered By – Deepak Tripathi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published