如何配置权限:仅允许用户单次查看单个实例,其余操作需特定权限
Solution to Adjust Card Access Permissions
Looking at your current permission class, the issue is that it enforces the same permission check for all API actions—so unpermitted users can't do anything, and permitted users can do everything. To meet your requirement (allow all authenticated users to view single instances, restrict other actions to users with specific permissions), we need to add logic that checks the current view action before applying permission rules.
Here's the adjusted permission class:
class IsCardAccess(BasePermission): def has_permission(self, request, view): # Allow all authenticated users to retrieve a single instance if view.action == 'retrieve': return request.user and request.user.is_authenticated # For all other actions (list, create, update, partial_update, destroy), require specific permissions if request.user and request.user.is_authenticated: return ( request.user.has_perm_extended(PERM_CARD_ACCESS) or request.user.has_perm_extended(PERM_CARD_SUPER_ACCESS) ) # Deny access for unauthenticated users to non-retrieve actions return False
Key Changes Explained:
- Single Instance View (retrieve): We first check if the current action is
retrieve(this corresponds to the GET request for a single instance, e.g.,/cards/1/). All authenticated users are allowed to perform this action, regardless of their specific card permissions.- If you want to allow unauthenticated users to view single instances too, just change the retrieve line to
return True.
- If you want to allow unauthenticated users to view single instances too, just change the retrieve line to
- Restricted Actions: For all other actions like
list(GET all instances),create(POST),update(PUT),partial_update(PATCH), anddestroy(DELETE), we enforce the original permission check—only users withPERM_CARD_ACCESSorPERM_CARD_SUPER_ACCESSare granted access. - Authentication Check: We keep the base authentication check to ensure only valid users can interact with the API (adjust the retrieve section if you need open access for anonymous users).
Notes:
- This assumes you're using Django REST Framework's standard viewset classes (like
ModelViewSet), which automatically set theview.actionattribute based on the request. If you're using custom views, make sure to set theactionattribute explicitly or adjust the logic to check the request method and URL pattern instead. - If you ever need to add more granular permissions (e.g., separate permissions for create vs. delete), you can extend this logic with additional
elif view.action == 'create'style checks.
内容的提问来源于stack exchange,提问作者Mykyta
相关产品推荐
相关产品推荐

