2012-10-08 22 views
0

如何顯示信息,沒有帖子,而不是404錯誤?沒有帖子信息,而是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)) 

回答

1

使用posts = get_list_or_404(Post, category__in=categories)你明確要求它返回一個404的情況下有沒有職位。

嘗試:

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)) 

並確保您打印出錯誤內by_category.html {{消息}}。

+1

我嘗試使用我的模板:{%if posts%} posts {%else%} No post {%endif%}。它也可以。哪裏做得更好:在視圖中還是在模板中?謝謝 – euro98

+0

如果你使用相同的模板,你應該在模板本身中實現它。 –

1

get_object_or_404僅僅是一個方便快捷,其主要目的是提高Http404

所以,如果你不想提出 404(我認爲這是你的問題),那麼你根本不應該使用快捷方式,而是自己處理情況。

東西沿着這些路線:

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

謝謝!很有幫助。 – euro98