Python django.shortcuts 模块,get_object_or_404() 实例源码

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

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def webfinger_view(request):
    """Generate a webfinger document."""
    q = request.GET.get("q")
    if not q:
        raise Http404()
    username = q.split("@")[0]
    if username.startswith("acct:"):
        username = username.replace("acct:", "", 1)
    user = get_object_or_404(User, username=username)
    # Create webfinger document
    webfinger = generate_legacy_webfinger(
        "diaspora",
        handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN),
        host=settings.SOCIALHOME_URL,
        guid=str(user.profile.guid),
        public_key=user.profile.rsa_public_key
    )
    return HttpResponse(webfinger, content_type="application/xrd+xml")
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def hcard_view(request, guid):
    """Generate a hcard document.

    For local users only.
    """
    try:
        profile = get_object_or_404(Profile, guid=guid, user__isnull=False)
    except ValueError:
        raise Http404()
    hcard = generate_hcard(
        "diaspora",
        hostname=settings.SOCIALHOME_URL,
        fullname=profile.name,
        firstname=profile.get_first_name(),
        lastname=profile.get_last_name(),
        photo300=profile.safer_image_url_large,
        photo100=profile.safer_image_url_medium,
        photo50=profile.safer_image_url_small,
        searchable="true" if profile.public else "false",
        guid=profile.guid,
        username=profile.user.username,
        public_key=profile.rsa_public_key,
    )
    return HttpResponse(hcard)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        """Redirect to user detail view if root page is a profile or if the user is logged in"""

        if settings.SOCIALHOME_HOME_VIEW:
            p, m = settings.SOCIALHOME_HOME_VIEW.rsplit('.', 1)
            return getattr(import_module(p), m).as_view()(request)

        if request.user.is_authenticated:
            landing_page = request.user.preferences.get("generic__landing_page")
            if landing_page == "profile":
                return ProfileDetailView.as_view()(request, guid=request.user.profile.guid)
            elif landing_page == "profile_all":
                return ProfileAllContentView.as_view()(request, guid=request.user.profile.guid)
            elif landing_page == "followed":
                return FollowedStreamView.as_view()(request)
            elif landing_page == "public":
                return PublicStreamView.as_view()(request)
            else:
                # Fallback to profile view
                return ProfileDetailView.as_view()(request, guid=request.user.profile.guid)
        if settings.SOCIALHOME_ROOT_PROFILE:
            profile = get_object_or_404(Profile, user__username=settings.SOCIALHOME_ROOT_PROFILE)
            return ProfileDetailView.as_view()(request, guid=profile.guid)
        return super(HomeView, self).get(request, *args, **kwargs)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def post_create_with_video(request):
    # POST???? video_pk?? ??
    video_pk = request.POST['video_pk']
    # ?? video_pk? ???? Video????
    video = get_object_or_404(Video, pk=video_pk)

    # ?? video? ?? Post??
    post = Post.objects.create(
        author=request.user,
        video=video,
    )
    # ??? Post??? my_comment? ???? Comment??
    post.my_comment = Comment.objects.create(
        post=post,
        author=request.user,
        content=video.title
    )
    return redirect('post:post_detail', post_pk=post.pk)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def restore_data(request):
    """
    Restores the password for user.
    """
    if request.method == 'POST':
        forgot_form = ForgotPasswordForm(request.POST)

        if forgot_form.is_valid():
            with transaction.atomic():
                temp_password = generate_password()

                user = get_object_or_404(User, email=forgot_form.cleaned_data['email'])
                user.set_password(temp_password)
                user.save()

                restore_account.delay(user.username, temp_password, forgot_form.cleaned_data['email'])

                logger.info("The password for user: '{}' restored successfully.".format(user))

                return HttpResponse(json.dumps(True), content_type='application/json')
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def find_book(request):
    """
    Generates list with books of data which user entered. At first it check full equality in name,
    after tries to check if contains some part of entered data.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    search_data = request.data.get('search_term')

    filtered_books = Book.exclude_private_books(user.id_user, Book.fetch_books(search_data))

    paginator = Paginator(filtered_books, OUTPUT_BOOKS_PER_PAGE)
    page = paginator.page(request.data.get('page'))
    next_page = page.has_next()
    page_books = page.object_list

    return Response({'status': 200,
                     'detail': 'successful',
                     'data': {'books': [BookSerializer(book).data for book in page_books],
                              'next_page': page.next_page_number() if next_page else 0}})
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def add_book_to_home(request):
    """
    Adds book to list of user's added books.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    book = get_object_or_404(Book, id=request.data.get('book_id'))

    if book.private_book and book.who_added != user:
        return Response({}, status=404)

    if AddedBook.objects.filter(id_user=user, id_book=book).exists():
        return Response({}, status=404)

    AddedBook.objects.create(id_user=user, id_book=book)
    logger.info("User '{}' added book with id: '{}' to his own library.".format(user.id_user.id, book.id))

    return Response({'status': 200,
                     'detail': 'success',
                     'data': {}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def remove_book_from_home(request):
    """
    Removes book from list of user's reading books.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    book = get_object_or_404(Book, id=request.data.get('book_id'))
    added_book = get_object_or_404(AddedBook, id_user=user, id_book=book)

    added_book.delete()
    logger.info("User '{}' removed book with id: '{}' from his own library."
                .format(request.user, request.data.get('book_id')))

    return Response({'status': 200,
                     'detail': 'success',
                     'data': {}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def open_book(request):
    """
    Returns the book of last readed page.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    book = get_object_or_404(Book, id=request.data.get('book_id'))

    added_book = get_object_or_404(AddedBook, id_book=book, id_user=user)
    added_book.last_read = added_book.last_read.now()
    added_book.save()

    logger.info("User '{}' opened book with id: '{}'.".format(user, book.id))

    return Response({'status': 200,
                     'detail': 'successful',
                     'data': {'last_page': added_book.last_page}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def set_current_page(request):
    """
    Changes current readed page for book of the user.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    book = get_object_or_404(Book, id=request.data.get('book_id'))
    current_page = request.data.get('current_page')

    if not isinstance(current_page, int):
        return Response({'status': 400,
                         'detail': 'current page not a number',
                         'data': {}}, status=400)

    added_book = AddedBook.objects.get(id_book=book, id_user=user)
    added_book.last_page = current_page
    added_book.save()

    logger.info("User '{}' on book with id: '{}' changed page to: '{}'."
                .format(user, book.id, current_page))

    return Response({'status': 200,
                     'detail': 'successful',
                     'data': {}})
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def category_detail(request, category_id):
    """
    Category detail
    ---
    serializer: categories.serializers.CategorySerializer
    responseMessages:
    - code: 400
      message: Bad request.
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    category = get_object_or_404(Category, pk=category_id)
    if request.method == 'GET':
        serializer = CategorySerializer(category)
        return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def keyword_detail(request, keyword_id):
    """
    Keyword detail
    ---
    serializer: categories.serializers.KeywordSerializer
    responseMessages:
    - code: 400
      message: Bad request.
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    keyword = get_object_or_404(Keyword, pk=keyword_id)
    if request.method == 'GET':
        serializer = KeywordSerializer(keyword)
        return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def employee(request, employee_id):
    """
    Returns employee details
    ---
    serializer: employees.serializers.EmployeeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        serializer = EmployeeSerializer(employee)
        return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def employee_activate(request, employee_id, action):
    """
    Activate employee account, action could be true or false
    ---
    response_serializer: employees.serializers.EmployeeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'PATCH':
        employee = get_object_or_404(Employee, pk=employee_id)
        if action == 'true':
            employee.is_active = True
        elif action == 'false':
            employee.is_active = False
        else:
            pass
        employee.save()
        serializer = EmployeeSerializer(employee)
        return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def employee_block(request, employee_id, action):
    """
    Block employee account, action could be true or false
    ---
    response_serializer: employees.serializers.EmployeeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'PATCH':
        employee = get_object_or_404(Employee, pk=employee_id)
        if action == 'true':
            employee.is_blocked = True
        elif action == 'false':
            employee.is_blocked = False
        else:
            pass
        employee.save()
        serializer = EmployeeSerializer(employee)
        return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def star(request, star_id):
    """
    Returns star detail
    ---
    serializer: stars.serializers.StarSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        star = get_object_or_404(Star, pk=star_id)
        serializer = StarSerializer(star)
        return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def stars_employee_list(request, employee_id):
    """
    Returns stars list from employee
    ---
    serializer: stars.serializers.StarSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_stars = Star.objects.filter(to_user=employee)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(employee_stars, request)
        serializer = StarSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def stars_employee_list_group_by_category(request, employee_id):
    """
    Returns stars list from employee grouped by categories
    ---
    serializer: stars.serializers.StarEmployeeCategoriesSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_stars = Star.objects.filter(to_user=employee).values(
            'category__pk',
            'category__name').annotate(num_stars=Count('category')).order_by('-num_stars', 'category__name')
        paginator = PageNumberPagination()
        result = paginator.paginate_queryset(employee_stars, request)
        serializer = StarEmployeeCategoriesSerializer(result, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def stars_employee_list_group_by_category_detail(request, employee_id, category_id):
    """
    Returns stars list detail from employee divided by category
    ---
    serializer: stars.serializers.StarSmallSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        category = get_object_or_404(Category, pk=category_id)
        stars = Star.objects.filter(to_user=employee, category=category).order_by('-date')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(stars, request)
        serializer = StarSmallSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def stars_employee_list_group_by_keyword_detail(request, employee_id, keyword_id):
    """
    Returns stars list detail from employee divided by keyword
    ---
    serializer: stars.serializers.StarSmallSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        keyword = get_object_or_404(Keyword, pk=keyword_id)
        stars = Star.objects.filter(to_user=employee, keyword=keyword).order_by('-date')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(stars, request)
        serializer = StarSmallSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def badges_employee_list(request, employee_id):
    """
    Returns badge list from employee
    ---
    response_serializer: stars.serializers.EmployeeBadgeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_bages = EmployeeBadge.objects.filter(to_user=employee)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(employee_bages, request)
        serializer = EmployeeBadgeSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def get_messages(request, employee_id):
    """
    Get all messages for employee id
    ---
    response_serializer: activities.serializers.MessageSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    - code: 500
      message: Internal Server Error
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        messages = Message.objects.filter(
            Q(to_user='all') |
            Q(to_user=employee.location.name) |
            Q(to_user=employee.username))
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(messages, request)
        serializer = MessageSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def get_messages_from(request, employee_id):
    """
    Get all messages sent from employee id
    ---
    response_serializer: activities.serializers.MessageSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    - code: 500
      message: Internal Server Error
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        messages = Message.objects.filter(from_user=employee)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(messages, request)
        serializer = MessageSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def get(self, request, event_id, format=None):
        """
        List all activities for an event
        ---
        serializer: administrator.serializers.EventActivitySerializer
        parameters:
        - name: pagination
          required: false
          type: string
          paramType: query
        """
        event = get_object_or_404(Event, pk=event_id)
        activities = EventActivity.objects.filter(event=event)
        if request.GET.get('pagination'):
            pagination = request.GET.get('pagination')
            if pagination == 'true':
                paginator = AdministratorPagination()
                results = paginator.paginate_queryset(activities, request)
                serializer = EventActivitySerializer(results, many=True)
                return paginator.get_paginated_response(serializer.data)
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            serializer = EventActivitySerializer(activities, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def get(self, request, employee_id, format=None):
        """
        List all messages from employee
        ---
        serializer: administrator.serializers.MessageSerializer
        parameters:
        - name: pagination
          required: false
          type: string
          paramType: query
        """
        employee = get_object_or_404(Employee, pk=employee_id)
        messages = get_list_or_404(Message, from_user=employee)
        if request.GET.get('pagination'):
            pagination = request.GET.get('pagination')
            if pagination == 'true':
                paginator = AdministratorPagination()
                results = paginator.paginate_queryset(messages, request)
                serializer = MessageSerializer(results, many=True)
                return paginator.get_paginated_response(serializer.data)
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            serializer = MessageSerializer(messages, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def delete(self, request, id, kind, format=None):
        """
        WARNING: Force delete
        """
        if kind == 'badge':
            kind = get_object_or_404(Badge, pk=id)
        elif kind == 'category':
            kind = get_object_or_404(Category, pk=id)
        elif kind == 'event':
            kind = get_object_or_404(Event, pk=id)
        elif kind == 'keyword':
            kind = get_object_or_404(Keyword, pk=id)
        elif kind == 'location':
            kind = get_object_or_404(Location, pk=id)
        elif kind == 'position':
            kind = get_object_or_404(Position, pk=id)
        elif kind == 'role':
            kind = get_object_or_404(Role, pk=id)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)

        kind.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def local_events(request, employee_id):
    """
    Returns the full upcoming events list for employee location
    ---
    serializer: events.serializers.EventSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        events = Event.objects.filter(location=employee.location, is_active=True)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(events, request)
        serializer = EventSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:BackendAllStars    作者:belatrix    | 项目源码 | 文件源码
def event_activities(request, event_id):
    """
    Returns activity list for event
    ---
    serializer: events.serializers.EventActivitySerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden.
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        event = get_object_or_404(Event, pk=event_id)
        activities = EventActivity.objects.filter(event=event)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(activities, request)
        serializer = EventActivitySerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)
项目:msdnhash    作者:mauricew    | 项目源码 | 文件源码
def family_detail(request, family_id):
    family = get_object_or_404(ProductFamily, pk=family_id)
    files = File.objects.filter(product_family_id= family.id).order_by("-posted_date", "description")
    file_languages = Language.objects.filter(file__product_family_id= family.id).order_by('name').distinct()

    lang = request.GET.get('lang')
    if lang:
        files = files.filter(language__code=lang)

    context = {
        'family': family,
        'files': files,
        'file_languages': file_languages,
        'selected_language': lang,
    }
    return render(request, 'msdn/family_detail.html', context)
项目:kuzgun.io    作者:yigitgenc    | 项目源码 | 文件源码
def retrieve(self, request, parent_lookup_torrent=None, *args, **kwargs):
        """
        Retrieve a file of the user.

        :return: Response
        """

        if parent_lookup_torrent:
            # Retrieve a file of the torrent.
            torrent = get_object_or_404(Torrent, pk=parent_lookup_torrent)
            if not torrent.finished:
                return Response({
                    'detail': "The torrent hasn't finished downloading yet.",
                    'progress': torrent.progress
                }, status=status.HTTP_400_BAD_REQUEST)

            file_obj = get_object_or_404(File, torrent__pk=parent_lookup_torrent, pk=kwargs.get('pk'))
            serializer = self.serializer_class(file_obj)

            return Response(serializer.data)

        return super(FileViewSet, self).retrieve(request, *args, **kwargs)
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def watch(request, poll_url):
    current_poll = get_object_or_404(Poll, url=poll_url)

    if not current_poll.can_watch(request.user, request):
        messages.error(
            request, _("You are not allowed to watch this poll.")
        )
        return redirect('poll', poll_url)

    if current_poll.user_watches(request.user):
        poll_watch = PollWatch.objects.get(poll=current_poll, user=request.user)
        poll_watch.delete()
    else:
        poll_watch = PollWatch(poll=current_poll, user=request.user)
        poll_watch.save()
    return redirect('poll', poll_url)
项目:openbare    作者:openbare    | 项目源码 | 文件源码
def checkin(request, primary_key):
    """Checkin the :model:`library.Lendable`.

    Cleanup and delete Lendable.

    Redirect:
    :view:`library.index`
    """
    item = get_object_or_404(Lendable.all_types,
                             pk=primary_key,
                             user=request.user)
    try:
        item.checkin()
    except Exception as e:
        messages.error(request, e)
    else:
        messages.success(request, "'%s' returned." % (item.name))
    return redirect(reverse('library:index'))
项目:TaleTellers    作者:lyk2017-django    | 项目源码 | 文件源码
def like(request):
    """
    kullan?c? be?endi?inde vya be?enmedi?inde ekrandaki skoru otomatik
    update eder
    """
    id = request.GET.get("id", default=None)
    like = request.GET.get("like")
    obj = get_object_or_404(Post, id=int(id))
    if like == "true":
        # f objesi veri tabanindaki ilgili sutunun degerini cekerek
        # atama yapmak yerine arttirma veya azaltma yapmamizi saglar.
        obj.score = F("score") + 1
        obj.save(update_fields=["score"])
    elif like == "false":
        obj.score = F("score") - 1
        obj.save(update_fields=["score"])
    else:
        return HttpResponse(status=400)
    obj.refresh_from_db()
    return JsonResponse({"like": obj.score, "id": id})
项目:django-tutorial    作者:fernandojunior    | 项目源码 | 文件源码
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice."
        })
    else:
        # See  Avoiding race conditions using F()
        # https://docs.djangoproject.com/en/1.9/ref/models/expressions/#avoiding-race-conditions-using-f
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(
            question.id,
        )))
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def plan_run_repo(request, plan_id, repo_owner, repo_name):
    plan = get_object_or_404(Plan, id=plan_id)
    repo = get_object_or_404(Repository, owner=repo_owner, name=repo_name)
    if request.method == 'POST':
        form = RunPlanForm(plan, repo, request.user, request.POST)
        if form.is_valid():
            build = form.create_build()
            return HttpResponseRedirect(build.get_absolute_url())
    else:
        form = RunPlanForm(plan, repo, request.user)
    context = {
        'form': form,
        'plan': plan,
        'repo': repo,
    }
    return render(request, 'plan/run.html', context=context)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def build_rebuild(request, build_id):
    build = get_object_or_404(Build, id=build_id)

    if not request.user.is_staff:
        return HttpResponseForbidden(
            'You are not authorized to rebuild builds')

    rebuild = Rebuild(
        build=build,
        user=request.user,
        status='queued',
    )
    rebuild.save()

    if not build.log:
        build.log = ''

    build.log += '\n=== Build restarted at {} by {} ===\n'.format(
        timezone.now(), request.user.username)
    build.current_rebuild = rebuild
    build.save()

    return HttpResponseRedirect('/builds/{}'.format(build.id))
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def test_method_peek(request, method_id):
    method = get_object_or_404(TestMethod, id=method_id)
    latest_fails = method.test_results.filter(
        outcome='Fail'
    ).order_by(
        '-build_flow__time_end'
    ).select_related(
        'build_flow',
        'build_flow__build',
        'build_flow__build__repo',
        'build_flow__build__plan',
        'build_flow__build__branch',
        'build_flow__build__branch__repo'
    )
    latest_fails = paginate(latest_fails, request)


    data = {
        'method': method,
        'latest_fails': latest_fails
    }

    return render(request, 'testresults/test_method_peek.html', data)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def repo_detail(request, owner, name):
    query = {
        'owner': owner,
        'name': name,
    }
    if not request.user.is_staff:
        query['public'] = True
    repo = get_object_or_404(Repository, **query)

    query = {'repo': repo}
    builds = view_queryset(request, query)
    context = {
        'repo': repo,
        'builds': builds,
    }
    return render(request, 'repository/repo_detail.html', context=context)
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def commit_detail(request, owner, name, sha):
    query = {
        'owner': owner,
        'name': name,
    }
    if not request.user.is_staff:
        query['public'] = True
    repo = get_object_or_404(Repository, **query)

    query = {'commit': sha, 'repo': repo}
    builds = view_queryset(request, query)

    context = {
        'repo': repo,
        'builds': builds,
        'commit': sha,
    }
    return render(request, 'repository/commit_detail.html', context=context)
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def form_valid(self, form, *args, **kwargs):
        product = get_object_or_404(Product, pk=self.kwargs['product_id'])
        quantity = form.cleaned_data['quantity']

        cart = get_cart(self.request, create=True)
        cart_item, cart_item_created = CartItem.objects.update_or_create(cart=cart, product=product)

        # If Cart item object has not been created  , amend quantity.
        if cart_item_created is False:
            cart_item.quantity += quantity
        else:
            cart_item.quantity = quantity

        cart_item.save()

        return super(AddToCartView, self).form_valid(form)
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def edit(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    if request.method == 'POST':
        form = IndividualForm(request.POST, instance=individual)
        if form.is_valid():
            form.save()
            return redirect('dashboard')
    #     form = IndividualForm(request.POST, request.FILES)
    #     if form.is_valid():
    #         individual = form.save(commit=False)
    #         individual.user = request.user
    #         individual.save()
    #         return redirect('dashboard')
    else:
        form = IndividualForm(instance=individual)

    return render(request, 'individuals/individual_form.html', {'form':form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def view(request, disease_id):
    disease = get_object_or_404(Disease, pk=disease_id)
    gene = disease.gene_set.all()[0]
    # print 'gene', gene.official_name
    # individuals = Individual.objects.all()
    individuals_variants = Variant.objects.filter(gene=gene.official_name)
    # individuals_variants = []
    # for individual in individuals:
    #     individual_variants = Variant.objects.filter(individual=individual, gene=gene.official_name)
    #     individuals_variants.append(individual_variants)
#    individual_variants.query.group_by = ['individual_id']
#    results = query.execute_sql()
#    individuals = Individual.objects.all()
#    for individual in individuals:
#        individual_variants = Variant.objects.find(filter(date__range=["2011-01-01", "2011-01-31"]))


    return render(request, 'diseases/view.html', {'disease': disease, 'variants': individuals_variants})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def edit(request, case_id):

    case = get_object_or_404(Case, pk=case_id)

    if request.method == 'POST':
        form = CaseForm(request.POST, request.FILES, instance=case)        
        if form.is_valid():
            form.save()
#            variants = form.cleaned_data['variants']
#            strs = form.cleaned_data['strs']
#            cnvs = form.cleaned_data['cnvs']
#            #use id for unique names
#            individual = Individual.objects.create(user=request.user, status='new')
#            
#            individual.variants=variants
#            individual.strs=cnvs
#            individual.cnvs=cnvs
#            
#            individual.name=request.POST['name']
#            individual.save()
#            AnnotateVariants.delay(individual.id)
            return redirect('cases_list')
    else:
        form = CaseForm(instance=case)
    return render(request, 'cases/edit.html', {'form': form})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def import_files(request, project_id):
    project = get_object_or_404(Project, pk=project_id)
    form = ImportFilesForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            for file in form.cleaned_data['file_list'].splitlines():
                # print(file)
                file_objs = File.objects.filter(name__contains=file)
                # print(file_obj)
                for file_obj in file_objs:
                    project.files.add(file_obj)
            # form.save()
            return redirect('projects-view', project.id)

    context = {'form': form, 'project': project}
    return render(request, 'projects/import_files.html', context)
项目:oglasi    作者:stralz    | 项目源码 | 文件源码
def wishlist_oglas(request, oglas_id):
    oglas = get_object_or_404(Oglas, pk=oglas_id)
    try:
        if oglas.na_wishlist:
            oglas.na_wishlist = False
        else:
            oglas.na_wishlist = True
        oglas.save()
    except (KeyError, Oglas.DoesNotExist):
        return JsonResponse({'success': False})
    else:
        return JsonResponse({'success': True})
项目:table_tennis_league    作者:ulternate    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(GameView, self).get_context_data(**kwargs)

        group = get_object_or_404(Group, id=self.kwargs.get('group_pk', None))
        game = get_object_or_404(Game, id=self.kwargs.get('game_pk', None))
        players = game.players.order_by('-ranking')
        for player in players:
            try:
                rank_change = str(player.rankchange_set.get(game=game))
            except RankChange.DoesNotExist:
                rank_change = 'not available'

            setattr(player, 'rank_change', rank_change)

        context.update({
            'group': group,
            'game': game,
            'players': players,
        })

        return context
项目:table_tennis_league    作者:ulternate    | 项目源码 | 文件源码
def form_valid(self, form):
        # Make sure only two players are selected.
        players = form.cleaned_data['players']
        if players.count() != 2:
            form.add_error(
                'players',
                'A game requires two players, please try again.',
            )
            return self.form_invalid(form)

        # Otherwise, connect the game to the group.
        self.object = form.save()
        group = get_object_or_404(Group, id=self.kwargs.get('pk', None))

        group.games.add(self.object)
        group.save()

        return HttpResponseRedirect(self.get_success_url())
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def content_xml_view(request, guid):
    """Diaspora single post view XML representation.

    Fetched by remote servers in certain situations.
    """
    content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC, local=True)
    entity = make_federable_content(content)
    xml = get_full_xml_representation(entity, content.author.private_key)
    return HttpResponse(xml, content_type="application/xml")
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def content_fetch_view(request, objtype, guid):
    """Diaspora content fetch view.

    Returns the signed payload for the public content. Non-public content will return 404.

    If the content is not local, redirect to content author server.

    Args:
        objtype (str) - Diaspora content type. Currently if it is `status_message`, `post` or `reshare`,
            we try to find `Content`.
        guid (str) - The object guid to look for.
    """
    if objtype not in ["status_message", "post", "reshare", "comment"]:
        raise Http404()
    content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC)
    if not content.local:
        url = "https://%s/fetch/%s/%s" % (
            content.author.handle.split("@")[1], objtype, guid
        )
        return HttpResponseRedirect(url)
    entity = make_federable_content(content)
    message = get_full_xml_representation(entity, content.author.private_key)
    document = MagicEnvelope(
        message=message, private_key=content.author.private_key, author_handle=content.author.handle
    )
    return HttpResponse(document.render(), content_type="application/magic-envelope+xml")
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        """Render ProfileDetailView for this user."""
        profile = get_object_or_404(Profile, user__username=kwargs.get("username"))
        return ProfileDetailView.as_view()(request, guid=profile.guid)