views:

13

answers:

1

I have used get_next_by_FOO inside my view to display an absolute url for the following item within a set of records however when it gets to the end of the query set an error is raised.

how do I stop my view from raising this error and instead just outputting some html letting me know that it has come to the end of the set?

All help is greatly appreciated.

Here is the error message, my view and template code.

Error

    Exception Type:     DoesNotExist
    Exception Value:    Body matching query does not exist.

View

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

Template

    <a href="{{ next.get_absolute_url }}">Next News</a></p>
    <a href="{{ pre.get_absolute_url }}">Previous News</a></p>
+3  A: 

The brute force answer is:

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

Template:

{% 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 %}
Mike DeSimone