英文:
How to all only post method in a view set in Django REST_framework?
问题
我有一个Django REST_framework API,我有一个UserViewSet类。对于这个视图集,我希望任何访问URL的人都可以使用Viewset的POST方法,但不能查看数据库中注册的所有用户。
这是我的views.py:
# 创建您的视图在这里。
class IsGetMethod(permissions.BasePermission):
def has_permission(self, request, view):
# 总是允许GET、HEAD或OPTIONS请求。
if request.method in permissions.SAFE_METHODS:
return False
else:
return True
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
permission_classes = [IsGetMethod]
当我这样做时,如果我没有进行身份验证,我无法使用GET方法(这是我想要的),但我也无法使用POST方法。
基本上,我希望在未进行身份验证时只有这个POST表单(在下面的红框中突出显示),而不是使用GET方法获取所有列表。GET方法应该只适用于已认证的管理员用户。
英文:
I have a Django REST_framework api and I have a UserViewSet class. For this view set I would like that anyone reaching the url can use the post method of the Viewset but cannot see all the users registered in the database.
Here is my views.py
# Create your views here.
class IsGetMethod(permissions.BasePermission):
def has_permission(self, request, view):
# Always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return False
else:
return True
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
permission_classes = [IsGetMethod]
When I do this, I cannot use the get method when I am not authenticated (which is what I want) but I can't neither use the post method.
Basically what I would like is to have only this post form when I am not authenticated. (highlighted in red below) and not all the list from the get method. The get method should be only for admin authenticated user.
答案1
得分: 0
基本上你可以使用POST方法,但主要问题是你正在通过发送GET请求的浏览器访问端点,然后你会收到权限错误。尝试使用Postman等工具来测试端点。
最后修改你的权限类:
def has_permission(self, request, view):
if (request.user and request.user.is_staff) or request.method == "POST":
return True
if request.method in SAFE_METHODS:
return False
else:
return True
英文:
basically you can use POST method but the main problem is that you are accessing endpoint with browser that sends a GET request first and you get permission error.Try using postman and so on for testing endpoints.
And finally modify your permission class:
def has_permission(self, request, view):
if (request.user and request.user.is_staff) or request.method == "POST":
return True
if request.method in SAFE_METHODS:
return False
else:
return True
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论