has_permission when the user is authenticated but not staff?from rest_framework.permissions import BasePermission class IsStaffUser(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_staff # Assume request.user.is_authenticated == True and request.user.is_staff == False class DummyUser: is_authenticated = True is_staff = False class DummyRequest: user = DummyUser() permission = IsStaffUser() result = permission.has_permission(DummyRequest(), None)
has_permission method returns based on the is_staff attribute.The has_permission method returns request.user.is_staff. Since the user is authenticated but not staff, is_staff is False. So the method returns False.
Option A uses the correct equality operator == and returns a boolean directly. Option A uses assignment = instead of comparison, causing a syntax error. Option A uses is which is not correct for string comparison. Option A misses a colon after the if statement, causing a syntax error.
from rest_framework.permissions import BasePermission class IsAdminUser(BasePermission): def has_permission(self, request, view): if request.user.username == 'admin': return True else: return False # But in testing, even user 'admin' is denied.
request.user might be if the user is not authenticated.If the user is not authenticated, request.user is an AnonymousUser which does not have a username attribute. Accessing request.user.username raises an AttributeError, so the permission denies access.
allowed after running this permission check?allowed?from rest_framework.permissions import BasePermission class IsAuthenticatedAndPost(BasePermission): def has_permission(self, request, view): return request.user.is_authenticated and request.method == 'POST' class DummyUser: is_authenticated = True class DummyRequest: user = DummyUser() method = 'POST' permission = IsAuthenticatedAndPost() allowed = permission.has_permission(DummyRequest(), None)
The user is authenticated (True) and the method is 'POST', so both conditions are True. The and operator returns True.
Custom permissions allow developers to enforce specific access rules tailored to their application's needs, such as checking user roles or request types. They do not replace authentication, generate docs, or manage database migrations.