Raise 404 and continue the URL chain

Oli picture Oli · Aug 19, 2009 · Viewed 32.8k times · Source

I've got a URLs pattern like this:

urlpatterns = (
    url(r'^$', list_titles, name='list'),
    url(r'^(?P<tag>[a-z\-0-9]+?)/$', list_titles, name='filtered-list'),
    url(r'^(?P<title>\S+?)/$', show_title, name='title'),
)

The filtered-list and title match the same things.

If there is an available list of things matching the tag in filtered-list, I want list_titles to fire off. But if there isn't a matching tag, I want to bubble that back to the URL processor so show_title fires off.

If there's no matching title, I'll raise a proper 404 there.

I know I can do this from inside the view...but it's a bit smelly having to hard-wire the process into the view. I'd like the URL order to decide what gets chosen first and what it hands off to.

Answer

c_harm picture c_harm · Aug 19, 2009

This is certainly view logic; all urls.py is for is for matching URL patterns, not performing validation. You can use the Http404 exception to handle this.

from django.http import Http404

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})

Alternatively, you may find the get_object_or_404 or get_list_or_404 methods, which shorten it up a bit.


Promised edit follows. Not exactly what you're looking for, but...

urlpatterns = (
    url(r'^$', list_titles, name='list'),
)

if 1=1: # Your logic here
    urlpatterns += ( url(r'^$', list_titles, name='list'), )

urlpatterns += (
    url(r'^(?P<title>\S+?)/$', show_title, name='title'),
    url(r'^spam/$', spam_bar),
    url(r'^foo/$', foo_bar),
}