Python rest_framework.generics.get_object_or_404() Examples

The following are 30 code examples of rest_framework.generics.get_object_or_404(). 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.generics , or try the search function .
Example #1
Source File: views.py    From open with MIT License 6 votes vote down vote up
def post(self, request, prompt_uuid):
        prompt = get_object_or_404(WriteUpPrompt, uuid=prompt_uuid)
        user = request.user

        serializer = WriteUpPromptVoteModifySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        validated_data = serializer.validated_data

        instance, created = WriteUpPromptVote.objects.update_or_create(
            user=user, prompt=prompt, defaults=validated_data
        )

        # Temporary hack, switch to a denormalized process that should
        # check and update this every five minutes instead
        prompt = instance.prompt
        prompt.score += 1
        prompt.save()

        return_serializer = WriteUpPromptVoteModifySerializer(instance=instance)
        return Response(data=return_serializer.data) 
Example #2
Source File: subscription_views.py    From silver with Apache License 2.0 6 votes vote down vote up
def get(self, request, format=None, **kwargs):
        subscription_pk = kwargs.get('subscription_pk', None)
        mf_product_code = kwargs.get('mf_product_code', None)

        subscription = Subscription.objects.get(pk=subscription_pk)

        metered_feature = get_object_or_404(
            subscription.plan.metered_features,
            product_code__value=mf_product_code
        )

        logs = MeteredFeatureUnitsLog.objects.filter(
            metered_feature=metered_feature.pk,
            subscription=subscription_pk)

        serializer = MFUnitsLogSerializer(
            logs, many=True, context={'request': request}
        )
        return Response(serializer.data) 
Example #3
Source File: views.py    From autoAdmin with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_object(self):
        queryset = Group.objects.all()
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
            'Expected view %s to be called with a URL keyword argument '
            'named "%s". Fix your URL conf, or set the `.lookup_field` '
            'attribute on the view correctly.' %
            (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)
        return obj 
Example #4
Source File: documents_views.py    From silver with Apache License 2.0 6 votes vote down vote up
def put(self, request, *args, **kwargs):
        doc_pk = kwargs.get('document_pk')
        entry_pk = kwargs.get('entry_pk')

        Model = self.get_model()
        model_name = self.get_model_name()

        document = get_object_or_404(Model, pk=doc_pk)
        if document.state != BillingDocumentBase.STATES.DRAFT:
            msg = "{model} entries can be added only when the {model_lower} is"\
                  " in draft state.".format(model=model_name,
                                            model_lower=model_name.lower())
            return Response({"detail": msg}, status=status.HTTP_403_FORBIDDEN)

        searched_fields = {model_name.lower(): document, 'pk': entry_pk}
        entry = get_object_or_404(DocumentEntry, **searched_fields)

        serializer = DocumentEntrySerializer(entry, data=request.data,
                                             context={'request': request})

        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data) 
Example #5
Source File: documents_views.py    From silver with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        doc_pk = kwargs.get('document_pk')
        entry_pk = kwargs.get('entry_pk')

        Model = self.get_model()
        model_name = self.get_model_name()

        document = get_object_or_404(Model, pk=doc_pk)
        if document.state != BillingDocumentBase.STATES.DRAFT:
            msg = "{model} entries can be deleted only when the {model_lower} is"\
                  " in draft state.".format(model=model_name,
                                            model_lower=model_name.lower())
            return Response({"detail": msg}, status=status.HTTP_403_FORBIDDEN)

        searched_fields = {model_name.lower(): document, 'pk': entry_pk}
        entry = get_object_or_404(DocumentEntry, **searched_fields)
        entry.delete()

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #6
Source File: subscription_views.py    From silver with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        sub = get_object_or_404(Subscription,
                                pk=kwargs.get('subscription_pk', None))
        if sub.state != Subscription.STATES.CANCELED:
            msg = 'Cannot reactivate subscription from %s state.' % sub.state
            return Response({"error": msg},
                            status=status.HTTP_400_BAD_REQUEST)
        else:
            sub.activate()
            sub.save()

            logger.debug('Reactivated subscription: %s', {
                'subscription': sub.id,
                'date': timezone.now().date().strftime('%Y-%m-%d'),
            })

            return Response({"state": sub.state},
                            status=status.HTTP_200_OK) 
Example #7
Source File: views.py    From betterself with MIT License 6 votes vote down vote up
def put(self, request, *args, **kwargs):
        data = request.data
        user = request.user

        try:
            uuid = data['uuid']
        except KeyError:
            raise Http404

        instance = get_object_or_404(self.model, user=user, uuid=uuid)
        serializer = self.update_serializer_class(instance, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
        else:
            return Response('Invalid Data Submitted {}'.format(data), status=400)

        return Response(serializer.data) 
Example #8
Source File: views.py    From betterself with MIT License 6 votes vote down vote up
def _get_analytics_dataframe(cls, user, supplement_uuid):
        supplement = get_object_or_404(Supplement, uuid=supplement_uuid, user=user)
        supplement_series = cls._get_daily_supplement_events_series_last_year(user, supplement)
        sleep_series = cls._get_sleep_series_last_year(user)
        productivity_series = cls._get_productivity_series_last_year(user)

        # if either sleep or productivity are empty, create an empty series that is timezone
        # aware (hence, matching the supplement index)
        if sleep_series.empty:
            sleep_series = pd.Series(index=supplement_series.index)

        if productivity_series.empty:
            productivity_series = pd.Series(index=supplement_series.index)

        dataframe_details = {
            'supplement': supplement_series,
            'sleep': sleep_series,
            'productivity': productivity_series
        }

        dataframe = pd.DataFrame(dataframe_details)
        return dataframe 
Example #9
Source File: api.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def reactions(self, request, pk):
        """route for POST /messages/{id}/reactions/ with body {"name":"emoji_name"}"""

        message = get_object_or_404(ConversationMessage, id=pk)
        self.check_object_permissions(self.request, message)

        data = {
            'message': pk,
            'name': request.data.get('name'),
            'user': request.user.id,
        }

        serializer = ConversationMessageReactionSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example #10
Source File: api.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def get_queryset(self):
        user_id = self.kwargs.get('pk', '')
        queryset = []

        if user_id:
            user = get_object_or_404(User, id=user_id)
        else:
            user = self.request.user

        for k, v in NodePermissionUtil.get_user_assets(user).items():
            if k.is_unixlike():
                system_users_granted = [s for s in v if s.protocol == 'ssh']
            else:
                system_users_granted = [s for s in v if s.protocol == 'rdp']
            k.system_users_granted = system_users_granted
            queryset.append(k)
        return queryset 
Example #11
Source File: transaction_views.py    From silver with Apache License 2.0 6 votes vote down vote up
def get_queryset(self):
        customer_pk = self.kwargs.get('customer_pk', None)

        payment_method_id = self.kwargs.get('payment_method_id')
        if payment_method_id:
            payment_method = get_object_or_404(PaymentMethod,
                                               id=payment_method_id,
                                               customer__pk=customer_pk)

            return Transaction.objects.filter(
                payment_method=payment_method
            )
        else:
            return Transaction.objects.filter(
                payment_method__customer__pk=customer_pk
            ) 
Example #12
Source File: api.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def get_queryset(self):
        user_id = self.kwargs.get('pk', '')
        queryset = []
        if not user_id:
            user = self.request.user
        else:
            user = get_object_or_404(User, id=user_id)

        nodes = NodePermissionUtil.get_user_nodes_with_assets(user)
        assets = {}
        for k, v in NodePermissionUtil.get_user_assets(user).items():
            if k.is_unixlike():
                system_users_granted = [s for s in v if s.protocol == 'ssh']
            else:
                system_users_granted = [s for s in v if s.protocol == 'rdp']
            assets[k] = system_users_granted
        for node, v in nodes.items():
            for asset in v['assets']:
                asset.system_users_granted = assets[asset]
            node.assets_granted = v['assets']
            queryset.append(node)
        return queryset 
Example #13
Source File: mixins.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def get_object_with_lock(self):
        """Return the object the view is displaying."""
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
            "Expected view %s to be called with a URL keyword argument "
            'named "%s". Fix your URL conf, or set the `.lookup_field` '
            "attribute on the view correctly."
            % (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        # NOTE: The line below was changed.
        obj = get_object_or_404(queryset.select_for_update(), **filter_kwargs)

        # May raise a permission denied.
        self.check_object_permissions(self.request, obj)

        return obj 
Example #14
Source File: user_profile_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_object(self):
        """Lookup user profile by pk or username"""
        lookup = self.kwargs.get(self.lookup_field, None)
        if lookup is None:
            raise ParseError(
                'Expected URL keyword argument `%s`.' % self.lookup_field
            )
        queryset = self.filter_queryset(self.get_queryset())

        try:
            pk = int(lookup)
        except (TypeError, ValueError):
            filter_kwargs = {'username': lookup}
        else:
            filter_kwargs = {'pk': pk}

        # Return a 404 if the user does not exist
        user = get_object_or_404(User, **filter_kwargs)
        # Since the user does exist, create a matching profile if necessary
        obj, created = queryset.get_or_create(user=user)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #15
Source File: user_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_object(self):
        """Lookup a  username by pk else use lookup_field"""
        queryset = self.filter_queryset(self.get_queryset())

        lookup = self.kwargs.get(self.lookup_field)
        filter_kwargs = {self.lookup_field: lookup}

        try:
            pk = int(lookup)
        except ValueError:
            pass
        else:
            filter_kwargs = {'pk': pk}

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #16
Source File: permissions.py    From micromasters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def has_permission(self, request, view):
        if request.user.is_anonymous:
            raise Http404

        user = get_object_or_404(
            User,
            social_auth__uid=view.kwargs['username'],
            social_auth__provider=EdxOrgOAuth2.name
        )

        # if the user is looking for their own profile, they're good
        if request.user == user:
            return True

        # if the user is looking for someone enrolled in a program they
        # are staff on, they're good
        if request.user.role_set.filter(
                role__in=(Staff.ROLE_ID, Instructor.ROLE_ID),
                program__programenrollment__user=user,
        ).exists():
            return True
        else:
            raise Http404 
Example #17
Source File: object_lookup_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_object(self):
        """
        Incase the lookup is on an object that has been hyperlinked
        then update the queryset filter appropriately
        """
        if self.kwargs.get(self.lookup_field, None) is None:
            raise ParseError(
                'Expected URL keyword argument `%s`.' % self.lookup_field
            )
        queryset = self.filter_queryset(self.get_queryset())

        filter_kwargs = {}
        serializer = self.get_serializer()
        lookup_field = self.lookup_field

        if self.lookup_field in serializer.get_fields():
            k = serializer.get_fields()[self.lookup_field]
            if isinstance(k, serializers.HyperlinkedRelatedField):
                lookup_field = '%s__%s' % (self.lookup_field, k.lookup_field)

        filter_kwargs[lookup_field] = self.kwargs[self.lookup_field]

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #18
Source File: views.py    From lego with MIT License 6 votes vote down vote up
def token(self, *arg, **kwargs):
        """
        Download the token belonging to a restricted mail. This token has to be attached to
        the restricted mail for authentication.
        """
        instance = get_object_or_404(RestrictedMail.objects.all(), id=kwargs["pk"])
        auth = self.request.GET.get("auth")

        if not instance.token_verify_query_param(auth):
            raise exceptions.AuthenticationFailed

        if not instance.token:
            raise exceptions.NotFound

        file_content = f"{RESTRICTED_TOKEN_PREFIX}{instance.token}"

        response = HttpResponse(file_content)
        response["Content-Disposition"] = 'attachment; filename="token"'
        return response 
Example #19
Source File: mixins.py    From drf-cached-instances with Mozilla Public License 2.0 6 votes vote down vote up
def get_object(self, queryset=None):
        """
        Return the object the view is displaying.

        Same as rest_framework.generics.GenericAPIView, but:
        - Failed assertions instead of deprecations
        """
        # Determine the base queryset to use.
        assert queryset is None, "Passing a queryset is disabled"
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        lookup = self.kwargs.get(lookup_url_kwarg, None)
        assert lookup is not None, "Other lookup methods are disabled"
        filter_kwargs = {self.lookup_field: lookup}
        obj = self.get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #20
Source File: utils.py    From MetaCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_object(self):
        """ return the object based on pk or slug """
        queryset = self.filter_queryset(self.get_queryset())

        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        lookup_value = self.kwargs[lookup_url_kwarg]

        filter_kwargs = {}
        if re.match(self.lookup_pk_regexp, lookup_value):
            filter_kwargs[self.lookup_field] = lookup_value
        else:
            filter_kwargs[self.lookup_slug_field] = lookup_value

        # May raise a permission denied
        obj = get_object_or_404(queryset, **filter_kwargs)
        self.check_object_permissions(self.request, obj)

        return obj 
Example #21
Source File: api.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def get_queryset(self):
        group_id = self.kwargs.get('pk', '')
        queryset = []

        if group_id:
            group = get_object_or_404(UserGroup, id=group_id)
            nodes = NodePermissionUtil.get_user_group_nodes(group)
            queryset = nodes.keys()
        return queryset 
Example #22
Source File: subscription_views.py    From silver with Apache License 2.0 5 votes vote down vote up
def get_object(self):
        customer_pk = self.kwargs.get('pk', None)
        return get_object_or_404(MeteredFeature, pk=customer_pk) 
Example #23
Source File: api.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def get_object(self):
        slug = self.kwargs['slug']
        if slug.startswith('p:'):
            return get_object_or_404(Position, secret=slug[2:])
        if slug.isdigit():
            location = get_location_by_id_for_request(slug, self.request)
            if isinstance(location, DynamicLocation):
                return location
        raise Http404 
Example #24
Source File: transaction_views.py    From silver with Apache License 2.0 5 votes vote down vote up
def get_object(self, **kwargs):
        transaction_uuid = kwargs.get('transaction_uuid')
        customer_pk = kwargs.get('customer_pk')

        return get_object_or_404(
            Transaction.objects.all(),
            uuid=transaction_uuid,
            payment_method__customer__pk=customer_pk
        ) 
Example #25
Source File: transaction_views.py    From silver with Apache License 2.0 5 votes vote down vote up
def get_object(self):
        transaction_uuid = self.kwargs.get('transaction_uuid', None)
        try:
            uuid = UUID(transaction_uuid, version=4)
        except ValueError:
            raise Http404

        return get_object_or_404(Transaction, uuid=uuid) 
Example #26
Source File: transaction_views.py    From silver with Apache License 2.0 5 votes vote down vote up
def perform_create(self, serializer):
        payment_method_id = self.kwargs.get('payment_method_id')
        if payment_method_id:
            payment_method = get_object_or_404(PaymentMethod,
                                               id=payment_method_id)
            serializer.save(payment_method=payment_method)
        else:
            serializer.save() 
Example #27
Source File: project.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def get_object(self):
        if self._object:
            return self._object
        self._object = get_object_or_404(Project, name=self.project_name,)
        return self._object 
Example #28
Source File: scans.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def scan_config(self):
        """
        Get the ScanConfig that this handler is referencing.
        :return: the ScanConfig that this handler is referencing.
        """
        if self._scan_config is None:
            self._scan_config = get_object_or_404(rest.models.ScanConfig, pk=self.kwargs["pk"])
        return self._scan_config 
Example #29
Source File: bindings.py    From channels-api with MIT License 5 votes vote down vote up
def get_object_or_404(self, pk):
        queryset = self.filter_queryset(self.get_queryset())
        filter_kwargs = {self.lookup_field: pk}
        try:
            return get_object_or_404(queryset, **filter_kwargs)
        except Http404:
            # transform Http404 into an APIException
            raise NotFound 
Example #30
Source File: views.py    From open with MIT License 5 votes vote down vote up
def delete(self, request, prompt_uuid):
        prompt = get_object_or_404(WriteUpPrompt, uuid=prompt_uuid)
        user = request.user

        instance = get_object_or_404(WriteUpFlaggedPrompt, prompt=prompt, user=user)
        instance.delete()

        return Response(status=204)