Raise 404 and continue the URL chain

谁说胖子不能爱 提交于 2019-12-04 22:16:24

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