我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用django.shortcuts.get_list_or_404()。
def employee_location_list(request): """ Returns employee location full list --- serializer: employees.serializers.EmployeeLocationListSerializer 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': location_list = get_list_or_404(Location) serializer = EmployeeLocationListSerializer(location_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def employee_role_list(request): """ Returns employee role full list --- serializer: employees.serializers.EmployeeRoleListSerializer 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': role_list = get_list_or_404(Role) serializer = EmployeeRoleListSerializer(role_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def evaluate_block_users(self): employees = get_list_or_404(Employee) for employee in employees: if employee.yesterday_given > config.MAX_STARS_GIVEN_DAY: employee.is_blocked = True if employee.yesterday_received > config.MAX_STARS_RECEIVED_DAY: employee.is_blocked = True if employee.current_month_given > config.MAX_STARS_GIVEN_MONTHLY: employee.is_blocked = True if employee.current_month_score > config.MAX_STARS_RECEIVED_MONTHLY: employee.is_blocked = True employee.save() try: if employee.is_blocked: self.send_blocked_notification_email(employee) send_push_notification(employee, config.USER_BLOCKED_NOTIFICATION_MESSAGE % employee.username) except Exception as e: print(e)
def get(self, request, format=None): """ List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string paramType: query """ badges = get_list_or_404(Badge) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(badges, request) serializer = BadgeSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = BadgeSerializer(badges, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, request, format=None): """ List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: false type: string paramType: query """ positions = get_list_or_404(Position) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(positions, request) serializer = PositionSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = PositionSerializer(positions, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def employee_deactivated_list(request, format=None): """ Returns the full employee deactivated list --- serializer: employees.serializers.EmployeeListSerializer 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_list = get_list_or_404(Employee, is_active=False) paginator = PageNumberPagination() results = paginator.paginate_queryset(employee_list, request) serializer = EmployeeListSerializer(results, many=True) return paginator.get_paginated_response(serializer.data)
def get(self, request, format=None): """ List all categories --- parameters: - name: pagination required: false type: string paramType: query """ categories = get_list_or_404(Category) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(categories, request) serializer = CategorySerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = CategorySerializer(categories, many=True) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): """ List all employees --- serializer: administrator.serializers.EmployeeSerializer parameters: - name: pagination required: false type: string paramType: query """ employees = get_list_or_404(Employee) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(employees, request) serializer = EmployeeSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = EmployeeSerializer(employees, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, request, format=None): """ List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string paramType: query """ events = get_list_or_404(Event) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(events, request) serializer = EventSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = EventSerializer(events, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, request, format=None): """ List all messages --- serializer: administrator.serializers.MessageSerializer parameters: - name: pagination required: false type: string paramType: query """ messages = get_list_or_404(Message) 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)
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)
def get(self, request, format=None): """ List all roles --- serializer: administrator.serializers.RoleSerializer parameters: - name: pagination required: false type: string paramType: query """ roles = get_list_or_404(Role) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(roles, request) serializer = RoleSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = RoleSerializer(roles, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def job_misclassify(request, id): instance = get_list_or_404(AllJobTitle, profile_id=id) id_instance = [job.id for job in instance] instance = [job.job for job in instance] form = JobMisClassify(request.POST or None, extra=instance) industry_map = {'software': 0, 'engineering': 1, 'research': 2, 'design': 3, 'data_science': 4, 'product_manager': 5, 'business_finance': 6, 'startup_founder': 7, 'admin_it': 8, 'crypto': 9} if form.is_valid(): for i in form.extra_answers(): i = list(i) if len(i[-1]) > 0: if i[-1] in industry_map.keys(): i[-1] = industry_map.get(i[-1]) index = instance.index(i[0]) job_id = id_instance[index] j = AllJobTitle.objects.get(id=job_id) j.job_classification = i[-1] j.save() return redirect('home') return render(request, 'job_misclassify.html', {'form':form})
def blog_search(request,): search_for = request.GET['search_for'] if search_for: results = [] article_list = get_list_or_404(Article) category_list = get_list_or_404(Category) for article in article_list: if re.findall(search_for, article.title): results.append(article) for article in results: article.body = markdown.markdown(article.body, ) tag_list = Tag.objects.all().order_by('name') return render(request, 'blog/search.html', {'article_list': results, 'category_list': category_list, 'tag_list': tag_list}) else: return redirect('app:index')
def get(self,request,*args,**kwargs): # These are passed via the URL year = self.kwargs.get('year') month = self.kwargs.get('month') slug = self.kwargs.get('slug','') try: month_number = list(month_name).index(month or 0) except ValueError: raise Http404(_('Invalid month.')) seriesset = get_list_or_404(Series,~Q(status=Event.RegStatus.hidden),~Q(status=Event.RegStatus.linkOnly),year=year or None,month=month_number or None,classDescription__slug=slug) # This will pass through to the context data by default kwargs.update({'seriesset': seriesset}) # For each Series in the set, add a button to the toolbar to edit the Series details if hasattr(request,'user') and request.user.has_perm('core.change_series'): for this_series in seriesset: this_title = _('Edit Class Details') if len(seriesset) > 1: this_title += ' (#%s)' % this_series.id request.toolbar.add_button(this_title, reverse('admin:core_series_change', args=([this_series.id,])), side=RIGHT) return super(IndividualClassView,self).get(request,*args,**kwargs)
def category_list(request): """ Returns full category list ordered by weight --- serializer: categories.serializers.CategorySerializer parameters: - name: pagination required: false type: string paramType: query 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': categories = get_list_or_404(Category, is_active=True) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = PageNumberPagination() results = paginator.paginate_queryset(categories, request) serializer = CategorySerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = CategorySerializer(categories, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def keyword_list(request): """ Returns full keyword list ordered by name --- serializer: categories.serializers.KeywordSerializer parameters: - name: pagination required: false type: string paramType: query 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': keywords = get_list_or_404(Keyword, is_active=True) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = PageNumberPagination() results = paginator.paginate_queryset(keywords, request) serializer = KeywordSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = KeywordSerializer(keywords, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def get_employee_list(self): default_image = File(open('sample_data/default_avatar.png', 'rb')) employees = get_list_or_404(Employee) for employee in employees: employee.avatar.save('default.png', default_image)
def change_month(self): employees = get_list_or_404(Employee) for employee in employees: employee.last_month_given = employee.current_month_given employee.last_month_score = employee.current_month_score employee.current_month_given = 0 employee.current_month_score = 0 employee.save()
def change_year(self): employees = get_list_or_404(Employee) for employee in employees: employee.last_year_given = employee.current_year_given employee.last_year_score = employee.current_year_score employee.current_year_given = 0 employee.current_year_score = 0 employee.save()
def change_day(self): employees = get_list_or_404(Employee) for employee in employees: employee.yesterday_given = employee.today_given employee.yesterday_received = employee.today_received employee.today_given = 0 employee.today_received = 0 employee.save()
def evaluate_event(self): today = timezone.now() events = get_list_or_404(Event) for event in events: if today.date() >= event.datetime.date(): event.is_upcoming = False event.save()
def get(self, request, format=None): """ List all keywords (tags, skills) or result list if you use ?search=term%of%search --- parameters: - name: search required: false type: string paramType: query - name: pagination required: false type: string paramType: query """ if request.GET.get('search'): request_terms = request.GET.get('search') search_terms_array = request_terms.split() initial_term = search_terms_array[0] keywords = Keyword.objects.filter(Q(name__icontains=initial_term)) if len(search_terms_array) > 1: for term in range(1, len(search_terms_array)): keywords = keywords.filter(Q(name__icontains=search_terms_array[term])) else: keywords = get_list_or_404(Keyword) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(keywords, request) serializer = KeywordSerializer(results, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer = KeywordSerializer(keywords, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def entry(request, word): chunks = get_list_or_404(Chunk, entry=word) entries = group_entries(chunks, separate_roots=True) assert len(entries) == 1 context = {'word': word, 'roots': [{'root': root.root, 'pos': root.pos, 'id': root.id, 'inflections': inflection_data(root), 'senses': root.senses} for root in entries[0].roots], 'url': request.build_absolute_uri(request.get_full_path()), 'request': request} return render(request, 'dictionary/entry.html', context)
def get(self,request,*args,**kwargs): # These are passed via the URL year = self.kwargs.get('year',timezone.now().year) month = self.kwargs.get('month',0) slug = self.kwargs.get('slug','') try: month_number = list(month_name).index(month) except ValueError: raise Http404(_('Invalid month.')) eventset = get_list_or_404(PublicEvent,~Q(status=Event.RegStatus.hidden),~Q(status=Event.RegStatus.linkOnly),year=year,month=month_number,slug=slug) # If an alternative link is given by one or more of these events, then redirect to that. overrideLinks = [x.link for x in eventset if x.link] if overrideLinks: return HttpResponseRedirect(overrideLinks[0]) # This will pass through to the context data by default kwargs.update({'eventset': eventset}) # For each Event in the set, add a button to the toolbar to edit the Event details if hasattr(request,'user') and request.user.has_perm('core.change_publicevent'): for this_event in eventset: this_title = _('Edit Event Details') if len(eventset) > 1: this_title += ' (#%s)' % this_event.id request.toolbar.add_button(this_title, reverse('admin:core_publicevent_change', args=([this_event.id,])), side=RIGHT) return super(IndividualEventView,self).get(request,*args,**kwargs) ##################################### # View for Repeating Events from admin
def collection_geojson(request, collection_id): collection = get_object_or_404(Collection, pk=collection_id) photos = get_list_or_404(collection.photo_set.all()) features = [f.get_geojson() for f in photos] d = { 'type': 'FeatureCollection', 'features': features } return JsonResponse(d)
def listing(request): tags = get_list_or_404(Tag) return render(request, 'tags/listing.html', dict( tags = tags, ))
def listing(request): sections = get_list_or_404(Section) return render(request, 'sections/listing.html', dict( sections = sections, ))
def listing(request): profiles = get_list_or_404(Profile) return render(request, 'profiles/listing.html', dict( profiles = profiles, ))
def listing(request, section): posts = get_list_or_404(Post, section=section) return render(request, 'posts/listing.html', dict( posts = posts, ))
def listing(request, section, id, slug): comments = get_list_or_404(Comment.objects.select_related('author', 'post', 'parent'), post=id) return render(request, 'comments/listing.html', dict( comments = comments, ))
def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] latest_question_list = get_list_or_404(Question.objects.order_by('-pub_date')[:5]) return render(request, 'polls/index.html', {'latest_question_list': latest_question_list})
def employee_list(request, format=None): """ Returns the full employee list or result list if you use ?search= --- serializer: employees.serializers.EmployeeListSerializer parameters: - name: search required: false type: string paramType: query 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': if request.GET.get('search'): request_terms = request.GET.get('search') search_terms_array = request_terms.split() initial_term = search_terms_array[0] employee_list = Employee.objects.filter( Q(first_name__icontains=initial_term) | Q(last_name__icontains=initial_term) | Q(username__icontains=initial_term)).filter(is_active=True, is_base_profile_complete=True) if len(search_terms_array) > 1: for term in range(1, len(search_terms_array)): employee_list = employee_list.filter( Q(first_name__icontains=search_terms_array[term]) | Q(last_name__icontains=search_terms_array[term]) | Q(username__icontains=search_terms_array[term])).filter( is_active=True, is_base_profile_complete=True) else: employee_list = get_list_or_404(Employee, is_active=True, is_base_profile_complete=True) paginator = PageNumberPagination() results = paginator.paginate_queryset(employee_list, request) serializer = EmployeeListSerializer(results, many=True) return paginator.get_paginated_response(serializer.data)
def edu_misclassify(request, id): instance = get_list_or_404(AllParsedProfile, id=id) # program = instance.school_program form = EducationMisClassify(request.POST or None) if form.is_valid(): print(form.cleaned_data) return redirect('home') return render(request, 'edu_misclassify.html', {'form':form, 'education':instance}) #def ind(request): # if request.method == 'POST': # form = AuthorForm(request.POST) # if form.is_valid(): # y = form.save() # print(form.cleaned_data.get('title')) # return redirect('home') # else: # form = AuthorForm() # if request.method == 'POST': # form = FormForm(request.POST) # if form.is_valid(): # print(form['e']) # return redirect('home') # else: # form = FormForm() # return render(request, 'index.html', {'form': form}) # # def signup(request): # if request.method == 'POST': # form = SignUpForm(request.POST) # if form.is_valid(): # user = form.save() # raw_password = form.cleaned_data.get('password1') # user = authenticate(username=user.username, password=raw_password) # login(request, user) # return redirect('home') # else: # form = SignUpForm() # return render(request, 'signup.html', {'form': form}) # def signup(request): # if request.method == 'POST': # form = UserCreationForm(request.POST) # if form.is_valid(): # user = form.save() # username = form.cleaned_data.get('username') # raw_password = form.cleaned_data.get('password1') # user = authenticate(username=username, password=raw_password) # login(request, user) # return redirect('home') # else: # form = UserCreationForm() # return render(request, 'signup.html', {'form': form})