Python rest_framework.decorators.action() Examples

The following are 30 code examples of rest_framework.decorators.action(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.decorators , or try the search function .
Example #1
Source File: api.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_queryset(self):
        if self.action in ('partial_update', 'thread'):
            return self.queryset
        qs = self.queryset \
            .with_conversation_access(self.request.user) \
            .annotate_replies_count() \
            .annotate_unread_replies_count_for(self.request.user)

        if self.action == 'my_threads':
            return qs.only_threads_with_user(self.request.user) \
                .prefetch_related('participants', 'latest_message')

        if self.action == 'list':
            qs = qs.prefetch_related('reactions', 'participants')

        if self.request.query_params.get('thread', None):
            return qs.only_threads_and_replies()

        return qs.exclude_replies() 
Example #2
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def to_representation(self, instance):
        ret = super().to_representation(instance)
        view = self.context['view']
        if view.action == 'retrieve':
            # get prev/next FieldValue id using the same sort order and filters from list view
            qs = view.get_queryset()
            qs = view.filter_queryset(qs)
            ids = list(qs.filter(field=instance.field).values_list('pk', flat=True))
            pos = ids.index(instance.pk)
            prev_ids = ids[:pos]
            next_ids = ids[pos + 1:]
            ret['prev_id'] = prev_ids[-1] if prev_ids else None
            ret['next_id'] = next_ids[0] if next_ids else None
            ret['annotations'] = FieldAnnotation.objects.filter(field=instance.field, document=instance.document) \
                .values('pk', 'location_start', 'location_end', 'location_text')
        return ret 
Example #3
Source File: users.py    From lego with MIT License 6 votes vote down vote up
def get_serializer_class(self):
        """
        Users should receive the DetailedUserSerializer if they tries to get themselves or have the
        EDIT permission.
        """
        if self.action in ["retrieve", "update", "partial_update"]:

            try:
                instance = self.get_object()
            except AssertionError:
                return PublicUserWithGroupsSerializer

            if (
                self.request.user.has_perm(EDIT, instance)
                or self.request.user == instance
            ):
                return MeSerializer

            return PublicUserWithGroupsSerializer

        elif self.action == "create":
            return RegistrationConfirmationSerializer

        return super().get_serializer_class() 
Example #4
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_annotations_queryset(self, only_true_annotations=False):
        """
        Get project annotations using SavedFilter logic to filter out FieldAnnotations*
        """
        project = self.get_object()

        request = HttpRequest()
        request.user = self.request.user
        request.GET = self.request.data

        from apps.document.api.v1 import DocumentFieldAnnotationViewSet as api_view
        view = api_view(request=request, kwargs={'project_pk': project.pk})
        view.action = 'list'

        qs = view.get_queryset(only_true_annotations=only_true_annotations)

        return qs 
Example #5
Source File: users.py    From lego with MIT License 6 votes vote down vote up
def update(self, request, *args, **kwargs):
        partial = kwargs.pop("partial", False)
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        is_abakus_member = serializer.validated_data.pop("is_abakus_member", None)
        with transaction.atomic():
            super().perform_update(serializer)
            if is_abakus_member is None or is_abakus_member == user.is_abakus_member:
                return Response(data=serializer.data, status=status.HTTP_200_OK)
            if not user.is_verified_student():
                raise ValidationError(
                    detail="You have to be a verified student to perform this action"
                )
            abakus_group = AbakusGroup.objects.get(name=constants.MEMBER_GROUP)
            if is_abakus_member:
                abakus_group.add_user(user)
            else:
                abakus_group.remove_user(user)
        payload = serializer.data
        payload["is_abakus_member"] = is_abakus_member
        return Response(data=payload, status=status.HTTP_200_OK) 
Example #6
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def assign_annotations(self, request, **kwargs):
        """
        Bulk assign batch of annotations to a review team member\n
            Params:
                annotation_ids: list[int]
                all: any value - update all annotations if any value
                no_annotation_ids: list[int] - exclude those annotations from action (if "all" is set)
                assignee_id: int
            Returns:
                int (number of reassigned annotations)
        """
        self.get_object()    # noqa: permissions check
        assignee_id = request.data.get('assignee_id')

        annotations = self.get_annotations_queryset()

        # re-fetch annotations as initial values-qs doesn't allow update
        ant_uids = [i['uid'] for i in annotations]
        true_annotations = FieldAnnotation.objects.filter(uid__in=ant_uids)
        true_annotations.update(assignee=assignee_id, assign_date=now())
        false_annotations = FieldAnnotationFalseMatch.objects.filter(uid__in=ant_uids)
        false_annotations.update(assignee=assignee_id, assign_date=now())

        return Response({'success': annotations.count()}) 
Example #7
Source File: views.py    From lego with MIT License 6 votes vote down vote up
def get_queryset(self):
        queryset = super().get_queryset()

        if self.action in ["popular", "list"]:
            # Usage count
            related_fields = [
                related.name for related in queryset.model._meta.related_objects
            ]
            annotation = Count(related_fields[0])
            for related in related_fields[1:]:
                annotation += Count(related)
            return queryset.annotate(usages=annotation)

        if self.action == "retrieve":
            # Usage count and relation counts
            related_fields = [
                related.name for related in queryset.model._meta.related_objects
            ]
            annotation = Count(related_fields[0])
            for related in related_fields[1:]:
                annotation += Count(related)
            annotations = {f"{field}_count": Count(field) for field in related_fields}
            return queryset.annotate(usages=annotation, **annotations)

        return queryset 
Example #8
Source File: views.py    From lego with MIT License 6 votes vote down vote up
def get_queryset(self):
        user = self.request.user
        if self.action in ["list", "upcoming"]:
            queryset = Event.objects.select_related("company").prefetch_related(
                "pools", "pools__registrations", "tags"
            )
        elif self.action == "retrieve":
            queryset = Event.objects.select_related(
                "company", "responsible_group"
            ).prefetch_related("pools", "pools__permission_groups", "tags")
            if user and user.is_authenticated:
                reg_queryset = self.get_registrations(user)
                queryset = queryset.prefetch_related(
                    "can_edit_users",
                    "can_edit_groups",
                    Prefetch("pools__registrations", queryset=reg_queryset),
                    Prefetch("registrations", queryset=reg_queryset),
                )
        else:
            queryset = Event.objects.all()
        return queryset 
Example #9
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_serializer_class(self, *args, **kwargs):
        if self.action == 'data' or self.request.method == 'PATCH':
            return DocumentDetailSerializer
        return DocumentsForUserSerializer 
Example #10
Source File: views.py    From djoser with MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == "create":
            self.permission_classes = settings.PERMISSIONS.user_create
        elif self.action == "activation":
            self.permission_classes = settings.PERMISSIONS.activation
        elif self.action == "resend_activation":
            self.permission_classes = settings.PERMISSIONS.password_reset
        elif self.action == "list":
            self.permission_classes = settings.PERMISSIONS.user_list
        elif self.action == "reset_password":
            self.permission_classes = settings.PERMISSIONS.password_reset
        elif self.action == "reset_password_confirm":
            self.permission_classes = settings.PERMISSIONS.password_reset_confirm
        elif self.action == "set_password":
            self.permission_classes = settings.PERMISSIONS.set_password
        elif self.action == "set_username":
            self.permission_classes = settings.PERMISSIONS.set_username
        elif self.action == "reset_username":
            self.permission_classes = settings.PERMISSIONS.username_reset
        elif self.action == "reset_username_confirm":
            self.permission_classes = settings.PERMISSIONS.username_reset_confirm
        elif self.action == "destroy" or (
            self.action == "me" and self.request and self.request.method == "DELETE"
        ):
            self.permission_classes = settings.PERMISSIONS.user_delete
        return super().get_permissions() 
Example #11
Source File: views.py    From djoser with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action == "create":
            if settings.USER_CREATE_PASSWORD_RETYPE:
                return settings.SERIALIZERS.user_create_password_retype
            return settings.SERIALIZERS.user_create
        elif self.action == "destroy" or (
            self.action == "me" and self.request and self.request.method == "DELETE"
        ):
            return settings.SERIALIZERS.user_delete
        elif self.action == "activation":
            return settings.SERIALIZERS.activation
        elif self.action == "resend_activation":
            return settings.SERIALIZERS.password_reset
        elif self.action == "reset_password":
            return settings.SERIALIZERS.password_reset
        elif self.action == "reset_password_confirm":
            if settings.PASSWORD_RESET_CONFIRM_RETYPE:
                return settings.SERIALIZERS.password_reset_confirm_retype
            return settings.SERIALIZERS.password_reset_confirm
        elif self.action == "set_password":
            if settings.SET_PASSWORD_RETYPE:
                return settings.SERIALIZERS.set_password_retype
            return settings.SERIALIZERS.set_password
        elif self.action == "set_username":
            if settings.SET_USERNAME_RETYPE:
                return settings.SERIALIZERS.set_username_retype
            return settings.SERIALIZERS.set_username
        elif self.action == "reset_username":
            return settings.SERIALIZERS.username_reset
        elif self.action == "reset_username_confirm":
            if settings.USERNAME_RESET_CONFIRM_RETYPE:
                return settings.SERIALIZERS.username_reset_confirm_retype
            return settings.SERIALIZERS.username_reset_confirm
        elif self.action == "me":
            return settings.SERIALIZERS.current_user

        return self.serializer_class 
Example #12
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ('create', 'update', 'partial_update'):
            return DocumentTypeCreateSerializer
        return DocumentTypeDetailSerializer 
Example #13
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        qs = super().get_queryset()

        project_pk = self.kwargs.get('project_pk')
        cluster_id = self.request.GET.get("cluster_id")

        if project_pk:
            qs = super().get_queryset().filter(project__pk=project_pk)

        if cluster_id:
            qs = qs.filter(cluster_id=int(cluster_id))

        if self.action == 'for_user':
            qs = qs.filter(assignee=self.request.user, status__group__is_active=True)

        elif self.action == 'retrieve':
            qs = qs.prefetch_related('documentnote_set')

        qs = qs \
            .select_related('status', 'status__group', 'document_type', 'assignee') \
            .defer('language', 'source', 'source_type', 'source_path',
                   'paragraphs', 'sentences', 'upload_session_id')

        qs = qs.annotate(assignee_name=F('assignee__username'),
                         status_name=F('status__name'))
        return qs 
Example #14
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def has_reviewer_permisson(request, view) -> Optional[bool]:
        if not request.user.is_reviewer:
            return None
        reviewer_actions = ['fields']
        if view.action not in reviewer_actions:
            return None
        # check project requested
        project_id = view.kwargs.get('project_pk')
        if not project_id:
            return None

        projects = project_api_module.Project.objects.filter(
            (Q(reviewers=request.user) | Q(super_reviewers=request.user)) &
            Q(pk=int(project_id)))
        return projects.exists() 
Example #15
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ('create', 'update', 'partial_update'):
            return DocumentFieldDetectorCreateSerializer
        return DocumentFieldDetectorDetailSerializer


# --------------------------------------------------------
# Document Type Views
# -------------------------------------------------------- 
Example #16
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        if self.context['view'].action == 'partial_update' and 'fields' not in self.context['request'].data:
            return instance
        return self.set_fields(instance) 
Example #17
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def to_representation(self, instance):
        ret = super().to_representation(instance)
        view = self.context['view']

        # inject next/prev annotation id into data
        if view.action == 'retrieve':
            # in case if queryset is ValuesQueryset instance
            if isinstance(instance, dict):
                instance = Map(instance)

            # get prev/next FieldAnnotation id using the same sort order and filters from list view
            view.kwargs['field_id'] = instance.field_id
            qs = view.get_queryset()

            id_set = [(i['uid'], i['document_id']) for i in qs]
            uids = [i[0] for i in id_set]

            pos = uids.index(instance.uid)
            prev_uids = uids[:pos]
            next_uids = uids[pos + 1:]
            ret['prev_id'] = prev_uids[-1] if prev_uids else None
            ret['next_id'] = next_uids[0] if next_uids else None
            ret['prev_document_id'] = id_set[:pos][-1][1] if prev_uids else None
            ret['next_document_id'] = id_set[pos + 1:][0][1] if next_uids else None

        return ret 
Example #18
Source File: admin.py    From django-restful-admin with MIT License 5 votes vote down vote up
def action(permission=None, methods=None, detail=None, url_path=None, url_name=None, **kwargs):
    def decorator(func):
        base_func = base_action(methods, detail, url_path, url_name, **kwargs)(func)
        base_func.permission = permission
        return base_func

    return decorator 
Example #19
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        self.initialize_request(request, *args, **kwargs)
        if self.action == 'retrieve':
            request.needs_action_logging = True
        return super().dispatch(request, *args, **kwargs) 
Example #20
Source File: views.py    From djoser with MIT License 5 votes vote down vote up
def get_queryset(self):
        user = self.request.user
        queryset = super().get_queryset()
        if settings.HIDE_USERS and self.action == "list" and not user.is_staff:
            queryset = queryset.filter(pk=user.pk)
        return queryset 
Example #21
Source File: views.py    From djoser with MIT License 5 votes vote down vote up
def permission_denied(self, request, message=None):
        if (
            settings.HIDE_USERS
            and request.user.is_authenticated
            and self.action in ["update", "partial_update", "list", "retrieve"]
        ):
            raise NotFound()
        super().permission_denied(request, message=message) 
Example #22
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action != "list":
            return TagDetailSerializer
        return super().get_serializer_class() 
Example #23
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ["create", "update", "partial_update"]:
            return RegistrationCreateAndUpdateSerializer
        if self.action == "retrieve":
            return RegistrationReadDetailedSerializer
        return super().get_serializer_class() 
Example #24
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ["create", "update", "partial_update"]:
            return SubmissionCreateAndUpdateSerializer
        if self.request and self.request.user.has_perm(EDIT, obj=Survey):
            return SubmissionAdminReadSerializer
        return SubmissionReadSerializer 
Example #25
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ["retrieve"]:
            return SurveyReadDetailedSerializer
        return SurveyReadSerializer 
Example #26
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ["create"]:
            return SurveyCreateSerializer
        elif self.action in ["update", "partial_update"]:
            return SurveyUpdateSerializer
        elif self.action in ["retrieve"]:
            user = self.request.user
            is_admin = user.has_perm(EDIT, obj=Survey)
            return (
                SurveyReadDetailedAdminSerializer
                if is_admin
                else SurveyReadDetailedSerializer
            )
        return SurveyReadSerializer 
Example #27
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def get_serializer_class(self):
        if self.action in ("update", "partial_update"):
            return MeetingInvitationUpdateSerializer
        return MeetingInvitationSerializer 
Example #28
Source File: users.py    From lego with MIT License 5 votes vote down vote up
def get_permissions(self):
        """
        The create action are used to register user, we do not require authentication on that
        endpoint.
        """
        if self.action == "create":
            return [AllowAny()]

        return super().get_permissions() 
Example #29
Source File: users.py    From lego with MIT License 5 votes vote down vote up
def get_queryset(self):
        if self.action == "retrieve":
            return self.queryset.prefetch_related("abakus_groups")
        return self.queryset 
Example #30
Source File: api.py    From marsha with MIT License 5 votes vote down vote up
def get_permissions(self):
        """Instantiate and return the list of permissions that this view requires."""
        if self.action == "metadata":
            permission_classes = [permissions.IsVideoToken]
        else:
            permission_classes = [
                permissions.IsVideoRelatedAdmin | permissions.IsVideoRelatedInstructor
            ]
        return [permission() for permission in permission_classes]