简体   繁体   English

权限:在django rest框架中

[英]permissions : in django rest framework

I m working on django rest framework. 我正在研究django rest框架。 I m having problems on permissions. 我在权限方面遇到问题。 I want to give GET And POST permission to admin user and only POST permission to other users(authentic). 我想向管理员用户授予GET和POST权限,并且只向其他用户授予POST权限(可靠)。 So far i have written the following code: 到目前为止,我已经编写了以下代码:

pemisssions.py pemisssions.py

class UserAccessPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET' or request.method == 'POST':
            return request.user and request.user.is_staff
        if request.method == 'POST':
            return request.user and request.user.is_authenticated()

This code is not working as expected. 此代码未按预期工作。 Only admin users are able to GET and POST. 只有管​​理员用户才能进行GET和POST。 And others users are not getting any kind of permission. 其他用户没有获得任何形式的许可。

Guys help. 伙计们帮忙。 Thanks in advance. 提前致谢。

EDITED EDITED

class UserAccessPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.method == 'POST':
            return request.user and request.user.is_authenticated()
        elif request.method == 'GET':
            return request.user and request.user.is_staff

There's a mistake in your conditions. 你的情况有误。 If it's a GEt request, the first condition always matches, which requires admin permissions. 如果是GEt请求,则第一个条件始终匹配,这需要管理员权限。

Here's what you want: 这是你想要的:

class UserAccessPermission(permissions.BasePermission):
    def has_permission(self, request, view):
    if request.method == 'POST':
            return request.user and request.user.is_authenticated()    
    elif request.method == 'GET': # no need to check for POST here
            return request.user and request.user.is_staff

您正在使用elif ,但不会评估此部分,因为如果方法是POST则第一个条件始终为True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM