简体   繁体   中英

permission to class some fields of ViewSet method Django rest framework

I want AllowAny permission only for the retrieve function. In my 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 .

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):
    ...
        ````

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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