You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置权限:仅允许用户单次查看单个实例,其余操作需特定权限

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.
  • Restricted Actions: For all other actions like list (GET all instances), create (POST), update (PUT), partial_update (PATCH), and destroy (DELETE), we enforce the original permission check—only users with PERM_CARD_ACCESS or PERM_CARD_SUPER_ACCESS are 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 the view.action attribute based on the request. If you're using custom views, make sure to set the action attribute 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:17:57