我在视图中使用了get_next_by_FOO来显示一组记录中的以下项目的绝对URL,但是当它到达查询集的末尾时会引发错误。
如何阻止我的视图引发此错误,而只是输出一些html让我知道它已经到了设置的末尾?
非常感谢所有帮助。
以下是错误消息,我的视图和模板代码。
错误
Exception Type: DoesNotExist
Exception Value: Body matching query does not exist.
查看
def news_view(request, url):
news = get_object_or_404(Body, url=url)
next = news.get_next_by_published()
pre = news.get_previous_by_published()
return render_to_response('news/news_view.html', {
'news': news,
'pre': pre,
'next': next
}, context_instance=RequestContext(request))
模板
<a href="{{ next.get_absolute_url }}">Next News</a></p>
<a href="{{ pre.get_absolute_url }}">Previous News</a></p>
答案 0 :(得分:4)
蛮力的答案是:
def news_view(request, url):
news = get_object_or_404(Body, url=url)
try:
next = news.get_next_by_published()
except Body.DoesNotExist:
next = None
try:
pre = news.get_previous_by_published()
except Body.DoesNotExist:
pre = None
return render_to_response('news/news_view.html', {
'news': news,
'pre': pre,
'next': next
}, context_instance=RequestContext(request))
模板:
{% if next %}<a href="{{ next.get_absolute_url }}">Next News</a></p>{% else %}<span class="disabled">At Last Item</span>{% endif %}
{% if pre %}<a href="{{ pre.get_absolute_url }}">Previous News</a></p>{% else %}<span class="disabled">At First Item</span>{% endif %}
答案 1 :(得分:4)
我这样做:
def news_view(request, url):
news = get_object_or_404(Body, url=url)
return direct_to_template(request, 'news/news_view.html', {'news': news,})
模板:
{% with news.get_previous_by_pub_date as prev %}
{% if prev %}
<a class="left btn" href="{{ prev.get_absolute_url }}">Previous News</a>
{% endif %}
{% endwith %}
{% with news.get_next_by_pub_date as next %}
{% if next %}
<a class="right btn" href="{{ next.get_absolute_url }}">Next News</a>
{% endif %}
{% endwith %}