python “POST”、“PUT”或“DELETE”不工作

ghhaqwfi  于 2023-02-18  发布在  Python
关注(0)|答案(2)|浏览(149)

在这里类WriteByAdminOnlyPermission是不是完美的工作。这个if request.method == 'GET':工作,但其余的条件是不工作。我的目标是,只有管理员可以改变信息和其他人只是可以看到。我怎么做呢?我做错了什么?请给予我一个相关的解决方案😥

***注意:***我在此处使用自定义用户

class User(AbstractUser):
    id = models.CharField(primary_key=True, max_length=10, default=uuid.uuid4, editable=False)

    email = models.EmailField(max_length=50, unique=True, error_messages={"unique":"The email must be unique!"})
    REQUIRES_FIELDS = ["email"]
    objects = CustomeUserManager()

浏览次数.py:

class WriteByAdminOnlyPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user

        if request.method == 'GET':
            return True

        if request.method in['POST','PUT','DELETE'] and user.is_superuser:
            return True
        return False

class ScenarioViewSet(ModelViewSet):
    permission_classes=[WriteByAdminOnlyPermission]
    serializer_class = ScenarioSerializer
    queryset = Scenario.objects.all()

型号.py:

class Scenario(models.Model):
    id = models.CharField(primary_key=True, max_length=10, default=uuid.uuid4, editable=False)
    Title = models.CharField(max_length=350, null=True, blank=False)
    film_id = models.OneToOneField(Film, on_delete=models.CASCADE, related_name="ScenarioFilmID", null=True)

序列化程序.py:

class ScenarioSerializer(ModelSerializer):
    class Meta:
        model = Scenario
        fields = "__all__"

网址.py:

router.register(r"scenario", views.ScenarioViewSet , basename="scenario")
ubof19bj

ubof19bj1#

为什么要在列表中使用or运算符,它可以简化为['POST', 'PUT', 'DELETE'],所以:

if request.method in ['POST', 'PUT', 'DELETE'] and user.is_superuser:

编辑

尝试直接使用IsAuthenticatedOrReadOnly类,以允许未经身份验证的用户执行GET请求,允许经过身份验证的用户执行POSTPUTDELETE请求,以便:

from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission

class WriteByAdminOnlyPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user

        if request.method in ['POST', 'PUT', 'DELETE'] and user.is_superuser:
            return True        
        return IsAuthenticatedOrReadOnly().has_permission(request, view)

class ScenarioViewSet(ModelViewSet):
    permission_classes = [WriteByAdminOnlyPermission]
    serializer_class = ScenarioSerializer
    queryset = Scenario.objects.all()
dgsult0t

dgsult0t2#

WriteByAdminOnlyPermission类的has_permission方法中,问题与以下条件有关:
if request.method in['POST' or 'PUT' or 'DELETE'] and user.is_superuser:
条件POSTPUTDELETE的计算结果始终为POST,因为or运算符在in运算符之前计算。因此,仅当request.method等于POSTuser.is_superuserTrue时,该条件才为true。要解决此问题,可以将条件更改为以下内容:
if request.method in ['POST', 'PUT', 'DELETE'] and user.is_superuser:
这将正确检查request.method是否为POSTPUTDELETE之一。
此外,请确保在项目中设置了正确的身份验证,以便正确设置request.user。

相关问题