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

Django REST API消费者用户资料权限控制实现需求问询

Solution for ConsumerProfilePermission Class

Got it, let's build that permission class to fit your exact requirements. Here's a complete implementation that covers all your access rules:

from rest_framework import permissions
from .models import Provider, Consumer  # 记得替换成你实际的模型导入路径

class ConsumerProfilePermission(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        # 管理员拥有完整权限,直接通过
        if request.user.is_staff:
            return True
        
        # 检查当前用户是否是该Consumer资料的所有者
        try:
            current_consumer = Consumer.objects.get(user=request.user)
            if current_consumer == obj:
                return True
        except Consumer.DoesNotExist:
            pass  # 当前用户不是Consumer,继续往下判断
        
        # 检查当前用户是Provider的话,仅允许只读操作
        try:
            Provider.objects.get(user=request.user)
            return request.method in permissions.SAFE_METHODS
        except Provider.DoesNotExist:
            pass  # 当前用户既不是管理员、所有者,也不是Provider
        
        # 剩下的情况(其他Consumer用户)直接拒绝访问
        return False

Let's break down the logic step by step:

  • Admin Access: First, we check if the user is a staff member—they get full access to everything, which is a common default for Django admin users.
  • Owner Access: We try to fetch the Consumer profile linked to the current user. If it matches the object being accessed, they can read and edit their own profile.
  • Provider Read-Only Access: If the user is a Provider (we check by fetching their linked Provider profile), we only allow safe HTTP methods (GET, HEAD, OPTIONS)—so they can view Consumer profiles but can't modify them.
  • Reject Other Consumers: Any other user (specifically, Consumers trying to access someone else's profile) gets denied entirely.

A couple of quick notes:

  • Make sure you're importing your actual Provider and Consumer models correctly (adjust the import path if needed).
  • This uses has_object_permission because we're dealing with object-level permissions (controlling access to individual Consumer profiles). If you need to control list-level access too, you can add a has_permission method as well (but your requirements focus on individual profiles, so this should suffice).

内容的提问来源于stack exchange,提问作者Zygro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:59:31