简体   繁体   English

对 class ViewSet 方法的某些字段的权限 Django rest 框架

[英]permission to class some fields of ViewSet method Django rest framework

I want AllowAny permission only for the retrieve function. In my ViewSets.我只需要AllowAny权限来retrieve function。在我的 ViewSets 中。

class PostLanguageViewSet(viewsets.ViewSet):

    permission_classes = (permissions.AllowAny,)

    permission_classes_per_method = {
        "retrieve": permission_classes
    }

    def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def destroy(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def update(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...
  • this method allows all function permission AllowAny .此方法允许所有 function 权限AllowAny

If you want to be specific to action and not method.如果你想具体到行动而不是方法。 You can check the action and apply the permission accordingly.您可以检查操作并相应地应用权限。

    class PostLanguageViewSet(viewsets.ViewSet):
        def get_permissions(self):
            if self.action == 'retrieve':
                return [permissions.AllowAny()]
            return super().get_permissions()

try this尝试这个

class PostLanguageViewSet(viewsets.ViewSet):
    def get_permissions(self):
        if self.request.method == 'GET':
            return [permissions.AllowAny()]
        else:
            return super().get_permissions()

You can use action decorator to achieve this this will override permissions and much more.您可以使用动作装饰器来实现这一点,这将覆盖权限等等。

class PostLanguageViewSet(viewsets.ViewSet):
    permission_classes = [permissions.AnyOtherPermissionForOtherMethods]

    @action(
        methods=("GET",),
        url_path="get-language",
        url_name="get-language",
        detail=True,
        permission_classes=[
            permissions.AllowAny],
    )
    def retrive_language(self, request, post_id=None, post_language_id=None, *args, **kwargs):
        #Your Code

    def destroy(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...

    def update(self, request, post_id=None, post_language_id=None, *args, **kwargs):
    ...
        ````

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

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