Python django.shortcuts.get_list_or_404() Examples

The following are 11 code examples for showing how to use django.shortcuts.get_list_or_404(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.shortcuts , or try the search function .

Example 1
Project: blog   Author: erenming   File: views.py    License: MIT License 6 votes vote down vote up
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') 
Example 2
Project: product-definition-center   Author: product-definition-center   File: views.py    License: MIT License 6 votes vote down vote up
def get_users_and_groups(resource_permission):
    group_popover = OrderedDict()
    inactive_user = {str(user.username) for user in models.User.objects.filter(is_active=False)}
    superusers_set = {str(user.username) for user in models.User.objects.filter(is_superuser=True)}
    try:
        group_resource_permission_list = get_list_or_404(models.GroupResourcePermission,
                                                         resource_permission=resource_permission)
        groups_list = [str(obj.group.name) for obj in group_resource_permission_list]
        for obj in groups_list:
            users_set = {str(user.username) for user in get_user_model().objects.filter(groups__name=obj)}
            users_list = sorted(users_set - inactive_user)
            group_popover.setdefault('@' + obj, users_list)
    except Http404:
        pass
    group_popover.setdefault('@superusers', sorted(superusers_set - inactive_user))
    return group_popover 
Example 3
Project: bridge-adaptivity   Author: harvard-vpal   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def preview_collection(request, slug):
    acitvities = [
        {
            'url': (
                f'{reverse("lti:source-preview")}?source_id={a.id}&source_name={urllib.parse.quote_plus(a.name)}'
                f'&source_lti_url={a.source_launch_url}&content_source_id={a.lti_content_source_id}'
            ),
            'pos': pos,
        }
        for pos, a in enumerate(get_list_or_404(Activity, collection__slug=slug), start=1)
    ]
    return render(
        request,
        template_name="module/sequence_preview.html",
        context={
            'activities': acitvities,
            'back_url': (
                f"{reverse('module:collection-detail', kwargs={'slug': slug})}"
                f"?back_url={request.GET.get('back_url')}"
            )
        }
    ) 
Example 4
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bad_class(self):
        # Given an argument klass that is not a Model, Manager, or Queryset
        # raises a helpful ValueError message
        msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
        with self.assertRaisesMessage(ValueError, msg):
            get_object_or_404("Article", title__icontains="Run")

        class CustomClass:
            pass

        msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'CustomClass'."
        with self.assertRaisesMessage(ValueError, msg):
            get_object_or_404(CustomClass, title__icontains="Run")

        # Works for lists too
        msg = "First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not 'list'."
        with self.assertRaisesMessage(ValueError, msg):
            get_list_or_404([Article], title__icontains="Run") 
Example 5
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bad_class(self):
        # Given an argument klass that is not a Model, Manager, or Queryset
        # raises a helpful ValueError message
        msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
        with self.assertRaisesMessage(ValueError, msg):
            get_object_or_404("Article", title__icontains="Run")

        class CustomClass:
            pass

        msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'CustomClass'."
        with self.assertRaisesMessage(ValueError, msg):
            get_object_or_404(CustomClass, title__icontains="Run")

        # Works for lists too
        msg = "First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not 'list'."
        with self.assertRaisesMessage(ValueError, msg):
            get_list_or_404([Article], title__icontains="Run") 
Example 6
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_faculty_or_404(allowed_units, userid_or_emplid):
    """
    Get the Person who has Role[role=~"faculty"] if we're allowed to see it, or raise Http404.
    """
    sub_unit_ids = Unit.sub_unit_ids(allowed_units)
    person = get_object_or_404(Person, find_userid_or_emplid(userid_or_emplid))
    roles = get_list_or_404(Role, role='FAC', unit__id__in=sub_unit_ids, person=person)
    units = set(r.unit for r in roles)
    return person, units 
Example 7
Project: drf-tracking   Author: aschn   File: views.py    License: ISC License 5 votes vote down vote up
def get(self, request):
        empty_qs = APIRequestLog.objects.none()
        return get_list_or_404(empty_qs) 
Example 8
Project: django-blog-it   Author: MicroPyramid   File: views.py    License: MIT License 5 votes vote down vote up
def get_queryset(self):
        self.tag = get_object_or_404(Tags, slug=self.kwargs.get("tag_slug"))
        return get_list_or_404(Post, tags=self.tag, status='Published', category__is_active=True) 
Example 9
Project: blog   Author: stormsha   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_queryset(self):
        # 重写通用视图的 get_queryset 函数,获取定制数据
        queryset = super(IndexView, self).get_queryset()

        # 日期归档
        year = self.kwargs.get('year', 0)
        month = self.kwargs.get('month', 0)

        # 标签
        tag = self.kwargs.get('tag', 0)

        # 导航条
        self.big_slug = self.kwargs.get('bigslug', '')

        # 文章分类
        slug = self.kwargs.get('slug', '')

        if self.big_slug:
            big = get_object_or_404(BigCategory, slug=self.big_slug)
            queryset = queryset.filter(category__bigcategory=big)

            if slug:
                slu = get_object_or_404(Category, slug=slug)
                queryset = queryset.filter(category=slu)

        if year and month:
            queryset = get_list_or_404(queryset, create_date__year=year, create_date__month=month)

        if tag:
            tags = get_object_or_404(Tag, name=tag)
            self.big_slug = BigCategory.objects.filter(category__article__tags=tags)
            self.big_slug = self.big_slug[0].slug
            queryset = queryset.filter(tags=tags)

        return queryset 
Example 10
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_list_or_404_queryset_attribute_error(self):
        """AttributeError raised by QuerySet.filter() isn't hidden."""
        with self.assertRaisesMessage(AttributeError, 'AttributeErrorManager'):
            get_list_or_404(Article.attribute_error_objects, title__icontains='Run') 
Example 11
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_list_or_404_queryset_attribute_error(self):
        """AttributeError raised by QuerySet.filter() isn't hidden."""
        with self.assertRaisesMessage(AttributeError, 'AttributeErrorManager'):
            get_list_or_404(Article.attribute_error_objects, title__icontains='Run')