Python rest_framework.generics 模块,get_object_or_404() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用rest_framework.generics.get_object_or_404()

项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
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
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
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
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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)
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_object(self):
        """ That override is to get 403 instead of 404 on single object ops

        Mostly a copy-paste from GenericAPIView
        """
        queryset = self.filter_queryset(self.model.objects.all())
        # 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]}
        obj = get_object_or_404(queryset, **filter_kwargs)
        # May raise a permission denied
        self.check_object_permissions(self.request, obj)
        return obj
项目:fire    作者:FundersClub    | 项目源码 | 文件源码
def approve(self, request, uuid=None):
        # We can't use `self.get_object()` because:
        # 1) It filters only for active repos and this one is potentially
        #    not active yet
        # 2) We want to always return a response even if the current user
        #    does not have access to this particular repo
        repo = get_object_or_404(models.Repository, uuid=uuid)

        # See if we're going to approve this repo
        if ((repo.status == models.Repository.Status.PendingInviterApproval) and
            (repo.inviter_login == request.user.username)):
            repo.approve_by_inviter(request.user)

        # Select which serializer class to use based on the current user's access
        serializer_class = RepositoryApproveSerializer
        if request.user in repo.admins.all():
            serializer_class = self.get_serializer_class()

        serializer = serializer_class(repo, context=self.get_serializer_context())
        return Response(serializer.data)


################################################################################
# Views
################################################################################
项目:ablator    作者:ablator    | 项目源码 | 文件源码
def get(self, request, client_user_string, functionality_group_id):
        """
        Is the specified user allowed to use the functionality?

        Returns `{ "enabled": true }` if the specified ClientUser is allowed to use the
        functionality group, ``{ "enabled": false }`` if the user is disallowed, or a 404 error if
        functionality group does not exist.

        Include a string that uniquely identifies the user as the client user string.

        See also the `which` endpoint to see if a user has a specific functionality group within a
        functionality
        """
        functionality_group = get_object_or_404(Functionality, id=functionality_group_id)
        client_user = ClientUser.user_from_object(client_user_string)
        return Response({'enabled': can_i_use(client_user, functionality_group)})
项目:ablator    作者:ablator    | 项目源码 | 文件源码
def get(self, request, client_user_string, functionality_group_id):
        """
        Which Flavor of the given Functionality is enabled for the user, if any?

        Returns `{ "which": "<app.group.functionality>" }` that corresponds to the ClientUser's
        enabled functionality, or `{ "which": none }` if the user does not have any Flavor in
        the given FuncationlityGroup.

        If the Functionality does not exist, this endpoint returns a 404 error.

        """
        functionality_group = get_object_or_404(Functionality, id=functionality_group_id)
        client_user = ClientUser.user_from_object(client_user_string)
        availability = which(client_user, functionality_group)
        return Response({
            'functionality': availability.flavor.__str__() if availability else None,
        })
项目:nhsuk-content-store    作者:nhsuk    | 项目源码 | 文件源码
def get_object(self):
        """
        Returns the page with id == the one passed in for a particular revision.

        The revision can be selected by using the query param `revision-id` which defaults to the latest one.
        """
        obj = super().get_object()

        revision_id = self.request.query_params.get('revision-id')
        if revision_id:
            revision = get_object_or_404(obj.revisions, id=revision_id)
        else:
            revision = obj.revisions.order_by('-created_at').first()

        # in case of no revisions, return the object (edge case)
        if not revision:
            return obj

        base = revision.as_page_object()
        return base.specific
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def get_object(self, queryset=None):
        """Lookup a  username by pk else use lookup_field"""
        if queryset is None:
            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
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def task_channel(self, request, task_id=None):
        """
        Gets or creates task channel
        ---
        response_serializer: ChannelSerializer
        """

        task = get_object_or_404(Task.objects.all(), pk=task_id)
        channel = None
        if task:
            channel = get_or_create_task_channel(request.user, task)
        if not channel:
            return Response(
                {'status': "Couldn't create task channel"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        response_serializer = ChannelSerializer(channel, context={'request': request})
        return Response(response_serializer.data)
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def update_read(self, request, pk=None):
        """
        Updates user's read_at for channel
        ---
        request_serializer: LastReadActivitySerializer
        response_serializer: ChannelSerializer
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        last_read = serializer.validated_data['last_read']
        channel = get_object_or_404(self.get_queryset(), pk=pk)
        if channel.has_object_read_permission(request):
            if request.user.is_authenticated():
                ChannelUser.objects.update_or_create(
                    user=request.user, channel=channel, defaults={'last_read': last_read}
                )
            else:
                channel.last_read = last_read
                channel.save()
            response_serializer = ChannelSerializer(channel, context={'request': request})
            return Response(response_serializer.data)
        return Response(
                {'status': 'Unauthorized', 'message': 'No access to this channel'},
                status=status.HTTP_401_UNAUTHORIZED
            )
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def update_read(self, request, pk=None):
        """
        Set message as last_read in it's channel
        ---
        response_serializer: ChannelSerializer
        """
        message = get_object_or_404(self.get_queryset(), pk=pk)

        if message.has_object_read_permission(request):
            ChannelUser.objects.update_or_create(
                user=request.user, channel=message.channel, defaults={'last_read': message.id}
            )
            response_serializer = ChannelSerializer(message.channel)
            return Response(response_serializer.data)
        return Response(
                {'status': 'Unauthorized', 'message': 'No access to this message'},
                status=status.HTTP_401_UNAUTHORIZED
            )
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def update_read(self, request, pk=None):
        """
        Updates user's read_at for channel
        ---
        request_serializer: LastReadActivitySerializer
        response_serializer: TaskSerializer
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        last_read = serializer.validated_data['last_read']
        task = get_object_or_404(self.get_queryset(), pk=pk)
        if task.has_object_read_permission(request):
            ActivityReadLog.objects.update_or_create(
                user=request.user,
                content_type=ContentType.objects.get_for_model(task), object_id=task.id,
                defaults={'last_read': last_read}
            )
            response_serializer = TaskSerializer(task, context={'request': request})
            return Response(response_serializer.data)
        return Response(
            {'status': 'Unauthorized', 'message': 'No access to this task'},
            status=status.HTTP_401_UNAUTHORIZED
        )
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def claim(self, request, pk=None):
        """
        Claim a project
        ---
        response_serializer: TaskSerializer
        """
        task = get_object_or_404(self.get_queryset(), pk=pk)
        if task.has_object_read_permission(request):
            task.pm = request.user
            task.save()
            response_serializer = TaskSerializer(task, context={'request': request})
            return Response(response_serializer.data)
        return Response(
            {'status': 'Unauthorized', 'message': 'No access to this task'},
            status=status.HTTP_401_UNAUTHORIZED
        )
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def return_project(self, request, pk=None):
        """
        Return a project
        ---
        request_serializer: None
        response_serializer: TaskSerializer
        """
        task = get_object_or_404(self.get_queryset(), pk=pk)
        if task.has_object_read_permission(request):
            task.pm = None
            task.save()
            response_serializer = TaskSerializer(task, context={'request': request})
            return Response(response_serializer.data)
        return Response(
            {'status': 'Unauthorized', 'message': 'No access to this task'},
            status=status.HTTP_401_UNAUTHORIZED
        )
项目:tunga-api    作者:tunga-io    | 项目源码 | 文件源码
def activity(self, request, pk=None):
        """
        Task Activity Endpoint
        ---
        response_serializer: SimpleActivitySerializer
        omit_parameters:
            - query
        """
        task = get_object_or_404(self.get_queryset(), pk=pk)
        self.check_object_permissions(request, task)

        queryset = ActionFilter(request.GET, self.filter_queryset(task.activity_stream.all().order_by('-id')))
        page = self.paginate_queryset(queryset.qs)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        self.profile = get_object_or_404(Profile, id=kwargs.get("id"))
        return super().dispatch(request, *args, **kwargs)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        self.profile = get_object_or_404(Profile, id=kwargs.get("id"))
        return super().dispatch(request, *args, **kwargs)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        self.tag = get_object_or_404(Tag, name=kwargs.get("name"))
        return super().dispatch(request, *args, **kwargs)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def post(self, request, post_pk):
        post_instance = get_object_or_404(Post, pk=post_pk)
        post_like, post_like_created = post_instance.postlike_set.get_or_create(
            user=request.user
        )
        if not post_like_created:
            post_like.delete()
        return Response({'created': post_like_created})
项目:kuzgun.io    作者:yigitgenc    | 项目源码 | 文件源码
def me(self, request):
        """
        Retrieves information of the user.

        :return: Response
        """
        user = get_object_or_404(self.queryset, pk=request.user.pk)
        serializer = self.get_serializer(user)

        return Response(serializer.data)
项目:zinc    作者:PressLabs    | 项目源码 | 文件源码
def destroy(self, request, pk=None):
        zone = get_object_or_404(models.Zone.objects, pk=pk)
        zone.soft_delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
项目:zinc    作者:PressLabs    | 项目源码 | 文件源码
def zone(self):
        zone_id = self.kwargs.get('zone_id')
        if zone_id is not None:
            queryset = self.get_queryset()
            return get_object_or_404(queryset, id=zone_id)
项目:zinc    作者:PressLabs    | 项目源码 | 文件源码
def list(self, request, zone_id):
        zone = get_object_or_404(models.Zone, id=zone_id)
        zone_data = ZoneDetailSerializer(zone, context={'request': request}).data
        return Response(zone_data['records'])
项目:zinc    作者:PressLabs    | 项目源码 | 文件源码
def get_object(self):
        zone_id = self.kwargs.get('zone_id')
        if zone_id is not None:
            return get_object_or_404(models.Zone, id=zone_id)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def get(self, request, username, *args, **kargs):  # pylint: disable=unused-argument
        """
        Returns information needed to display the user
        dashboard for all the programs the user is enrolled in.
        """
        user = get_object_or_404(
            User,
            social_auth__uid=username,
            social_auth__provider=EdxOrgOAuth2.name
        )

        # get the credentials for the current user for edX
        edx_client = None
        if user == request.user:
            user_social = get_social_auth(request.user)
            try:
                utils.refresh_user_token(user_social)
            except utils.InvalidCredentialStored as exc:
                return Response(
                    status=exc.http_status_code,
                    data={'error': str(exc)}
                )
            except:  # pylint: disable=bare-except
                log.exception('Impossible to refresh user credentials in dashboard view')
            # create an instance of the client to query edX
            edx_client = EdxApi(user_social.extra_data, settings.EDXORG_BASE_URL)

        try:
            program_dashboard = get_user_program_info(user, edx_client)
        except utils.InvalidCredentialStored as exc:
            log.exception('Access token for user %s is fresh but invalid; forcing login.', user.username)
            return Response(
                status=exc.http_status_code,
                data={'error': str(exc)}
            )
        return Response(
            status=status.HTTP_200_OK,
            data=program_dashboard
        )
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def has_permission(self, request, view):
        """
        Implementation of the permission class.
        """
        profile = get_object_or_404(Profile, user__social_auth__uid=view.kwargs['user'])

        if request.user == profile.user:
            return True

        # If viewer is instructor or staff in the program, skip this check
        if not request.user.is_anonymous() and request.user.role_set.filter(
                role__in=(Staff.ROLE_ID, Instructor.ROLE_ID),
                program__programenrollment__user__profile=profile,
        ).exists():
            return True

        # private profiles
        if profile.account_privacy == Profile.PRIVATE:
            raise Http404
        elif profile.account_privacy == Profile.PUBLIC_TO_MM:
            # anonymous user accessing profiles.
            if request.user.is_anonymous():
                raise Http404
            # requesting user must have enrollment in one of program where profile user is enroll.
            program_ids = ProgramEnrollment.objects.filter(user=profile.user).values_list('program__id', flat=True)
            if not ProgramEnrollment.objects.filter(user=request.user, program__id__in=program_ids).exists():
                raise Http404
        elif profile.account_privacy not in [Profile.PRIVATE, Profile.PUBLIC_TO_MM, Profile.PUBLIC]:
            raise Http404

        return True
项目:channels-api    作者:linuxlewis    | 项目源码 | 文件源码
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
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def get_object(self, prefetch=True):
        """
        Returns the object the view is displaying.
        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        queryset = self.filter_queryset(self.get_queryset(prefetch=prefetch))

        # 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]}
        obj = get_object_or_404(queryset, **filter_kwargs)

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

        return obj
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def retrieve(self, request, pk):
        queryset = self.get_queryset()
        instance = get_object_or_404(queryset, pk=pk)
        children = queryset.filter(parent=instance)

        parent_serializer = self.get_serializer(instance)
        parent_data = parent_serializer.data
        child_serializer = self.get_serializer(children, many=True)
        parent_data['children'] = child_serializer.data

        return Response(parent_data)
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
def delete(self, request, *args, **kwargs):
        try:
            uuid = request.data['uuid']
        except KeyError:
            raise Http404

        filter_params = {
            'uuid': uuid,
            'user': request.user
        }

        get_object_or_404(self.model, **filter_params).delete()
        return Response(status=204)
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
def get(self, request, supplement_uuid):
        supplement = get_object_or_404(Supplement, uuid=supplement_uuid, user=request.user)
        user = request.user

        serializer = SupplementLogRequestParametersSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        params = serializer.validated_data

        start_date = params['start_date']
        end_date = get_current_userdate(user)

        supplement_events = SupplementLog.objects.filter(user=user, supplement=supplement, time__date__gte=start_date)

        builder = SupplementEventsDataframeBuilder(supplement_events)
        if params['frequency'] == 'daily':
            # most of the time the dataframe contains a lot of supplements, here we are only picking one
            try:
                series = builder.get_flat_daily_dataframe()[supplement.name]
            except KeyError:
                # key error for no data if the supplement was never taken during this time
                series = pd.Series()

            if params['complete_date_range_in_daily_frequency']:
                series = force_start_end_date_to_series(user, series, start_date, end_date)

        else:
            df = builder.build_dataframe()
            series = df['Quantity']

        json_data = series.to_json(date_format='iso')
        data = json.loads(json_data)
        return Response(data)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def get_object(self):
        formId = self.request.GET.get('formId', '')
        id_string = _extract_id_string(formId)
        uuid = _extract_uuid(formId)
        username = self.kwargs.get('username')

        obj = get_object_or_404(Instance,
                                xform__user__username__iexact=username,
                                xform__id_string__exact=id_string,
                                uuid=uuid)
        self.check_object_permissions(self.request, obj.xform)

        return obj
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def create(self, request, *args, **kwargs):
        if request.method.upper() == 'HEAD':
            return Response(status=status.HTTP_204_NO_CONTENT,
                            headers=self.get_openrosa_headers(request),
                            template_name=self.template_name)

        xform_def = request.FILES.get('form_def_file', None)
        response_status = status.HTTP_201_CREATED
        username = kwargs.get('username')
        form_user = (username and get_object_or_404(User, username=username)) \
            or request.user

        if not request.user.has_perm(
            'can_add_xform',
            UserProfile.objects.get_or_create(user=form_user)[0]
        ):
            raise exceptions.PermissionDenied(
                detail=_(u"User %(user)s has no permission to add xforms to "
                         "account %(account)s" %
                         {'user': request.user.username,
                          'account': form_user.username}))
        data = {}

        if isinstance(xform_def, File):
            do_form_upload = DoXmlFormUpload(xform_def, form_user)
            dd = publish_form(do_form_upload.publish)

            if isinstance(dd, XForm):
                data['message'] = _(
                    u"%s successfully published." % dd.id_string)
            else:
                data['message'] = dd['text']
                response_status = status.HTTP_400_BAD_REQUEST
        else:
            data['message'] = _(u"Missing xml file.")
            response_status = status.HTTP_400_BAD_REQUEST

        return Response(data, status=response_status,
                        headers=self.get_openrosa_headers(request,
                                                          location=False),
                        template_name=self.template_name)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def retrieve(self, request, pk=None):
        queryset = UserProfile.objects.all()
        if pk is not None:
            profile = get_object_or_404(queryset, pk=pk)
        else:
            profile = UserProfile.objects.get(user=request.user)
        serializer = UserSerializerProfile(profile)
        return Response(serializer.data)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def validate(self, attrs):
        email_or_username = attrs.get('email_or_username')
        password = attrs.get('password')

        if email_or_username and password:
            # Check if user sent email
            if validateEmail(email_or_username):
                user_request = get_object_or_404(
                    User,
                    email=email_or_username,
                )

                email_or_username = user_request.username

            user = authenticate(username=email_or_username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise ValidationError(msg)
        else:
            msg = _('Must include "email or username" and "password"')
            raise ValidationError(msg)

        attrs['user'] = user
        return attrs


# class ProfileSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = UserProfile
#         exclude = ('user', 'id', 'organization')
#
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def pre_save(self, obj):
        """
        Set any attributes on the object that are implicit in the request.
        """
        # pk and/or slug attributes are implicit in the URL.
        lookup = self.kwargs.get(self.lookup_field, None)
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        slug = self.kwargs.get(self.slug_url_kwarg, None)
        slug_field = slug and self.slug_field or None

        if lookup:
            serializer = self.get_serializer()
            k = serializer.get_fields()[self.lookup_field]
            queryset = self.get_queryset()
            queryset = self.filter_queryset(queryset)
            if isinstance(k, serializers.HyperlinkedRelatedField):
                filter = {}
                lookup_field = '%s__%s' % (self.lookup_field, k.lookup_field)
                filter[lookup_field] = lookup
                k_obj = get_object_or_404(queryset, **filter)
                lookup = getattr(k_obj, self.lookup_field)
            setattr(obj, self.lookup_field, lookup)

        if pk:
            setattr(obj, 'pk', pk)

        if slug:
            setattr(obj, slug_field, slug)

        # Ensure we clean the attributes so that we don't eg return integer
        # pk using a string representation, as provided by the url conf kwarg.
        if hasattr(obj, 'full_clean'):
            exclude = mixins._get_validation_exclusions(
                obj, pk, slug_field, self.lookup_field)
            obj.full_clean(exclude)
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_parent_object(self, pk):
        parent_obj = get_object_or_404(self.parent_model, pk=pk)
        self.check_object_permissions(self.request, parent_obj)
        return parent_obj
项目:fire    作者:FundersClub    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        self.msg = get_object_or_404(
            fb_emails_models.IncomingMessage,
            uuid=kwargs['msg_uuid'],
        )
        self.repo = self.msg.issue.repo
        return super().dispatch(request, *args, **kwargs)
项目:coderplex-backend    作者:coderplex    | 项目源码 | 文件源码
def get_object(self):
        return get_object_or_404(
            Chapter,
            book__slug=self.kwargs['book'],
            slug=self.kwargs['chapter'])
项目:coderplex-backend    作者:coderplex    | 项目源码 | 文件源码
def get_object(self):
        return get_object_or_404(
            Page,
            chapter__slug=self.kwargs['chapter'],
            slug=self.kwargs['slug'])
项目:instanotifier    作者:AlexanderKaluzhny    | 项目源码 | 文件源码
def get_object(self):
        pk = self.request.data.get('id')
        queryset = self.filter_queryset(self.get_queryset())
        obj = get_object_or_404(queryset, pk=pk)
        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj
项目:Social    作者:vijayendra    | 项目源码 | 文件源码
def perform_create(self, serializer):
        post = generics.get_object_or_404(Post, pk=self.kwargs['post'])
        serializer.save(user=self.request.user, post=post)
项目:sh8email-django    作者:triplepy    | 项目源码 | 文件源码
def _get_object(request, nickname, pk):
        # TODO DUP CODE. Must refactor this.
        try:
            mail = get_object_or_404(Mail, pk=pk)
            can_read = mail.can_read(request)
            if mail.recipient != nickname:
                return None
            if can_read == (True, None):
                mail.read()
                return mail
            elif can_read == (False, {CannotReadReasons.secret_code}):
                return None
            return None
        except Mail.DoesNotExist:
            return None
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def get_object(self):
        """
        Returns the object the view is displaying.

        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        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)
        )

        try:
            obj = queryset.get(**{self.lookup_field: self.kwargs[lookup_url_kwarg]})
        except (ObjectDoesNotExist, ValidationError, TypeError, ValueError):
            obj = get_object_or_404(queryset, nb_id=self.kwargs[lookup_url_kwarg])

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

        return obj
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def get_object(self, queryset=None):
        """Lookup user profile by pk or username"""
        if self.kwargs.get(self.lookup_field, None) is None:
            raise ParseError(
                'Expected URL keyword argument `%s`.' % self.lookup_field
            )
        if queryset is None:
            queryset = self.filter_queryset(self.get_queryset())

        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)

        lookup = self.kwargs[self.lookup_field]
        filter_kwargs = {lookup_field: lookup}

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

        obj = get_object_or_404(queryset, **filter_kwargs)

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

        return obj