Raise 404 and continue the URL chain

匆匆过客 提交于 2019-12-06 16:36:51

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/1299701/raise-404-and-continue-the-url-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!