Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 没有发布信息,而是404错误_Django - Fatal编程技术网

Django 没有发布信息,而是404错误

Django 没有发布信息,而是404错误,django,Django,如何显示没有post而不是404错误的信息 这种事情在django发生的频率是多少 def post_by_category(request, slug): category = get_object_or_404(Category, slug=slug) categories = category.get_descendants(include_self=True) posts = get_list_or_404(Post, category__in=categorie

如何显示没有post而不是404错误的信息

这种事情在django发生的频率是多少

def post_by_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    categories = category.get_descendants(include_self=True)
    posts = get_list_or_404(Post, category__in=categories)

    return render_to_response("by_category.html",
                              {'posts': posts, context_instance=RequestContext(request))
只是一个方便快捷方式,其主要目的是提出一个
Http404

因此,如果你不想提出404(我想这是你的问题),那么你不应该使用捷径,而应该自己处理这种情况

大致如下:

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        # render whatever you like

通过使用
posts=get\u list\u或_404(Post,category\u in=categories)
您明确要求它在没有帖子的情况下返回404

尝试:


并确保您在
by_category.html

中打印出错误{{message},我在我的模板中尝试:{%if posts%}posts{%else%}无post{%endif%}。它也起作用。在哪里做得更好:在视图中还是在模板中?谢谢如果您使用的是同一个模板,那么您应该在模板本身中实现这一点。
posts = Post.objects.filter(category__in=categories)
if posts:
    return render_to_response("by_category.html",
                              {'posts': posts}, context_instance=RequestContext(request))
else:
    return render_to_response("by_category.html",
                              {'message': 'No posts found!'}, context_instance=RequestContext(request))