引发 404 并继续 URL 链 [英] Raise 404 and continue the URL chain
问题描述
我有一个像这样的 URL 模式:
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'),
)
filtered-list
和 title
匹配相同的东西.
The filtered-list
and title
match the same things.
如果在 filtered-list
中有与 tag
匹配的可用列表,我希望 list_titles
触发.但是,如果没有匹配的 tag
,我想将其返回给 URL 处理器,以便 show_title
触发.
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.
如果没有匹配的标题,我会在那里提出适当的 404.
If there's no matching title, I'll raise a proper 404 there.
我知道我可以从视图内部执行此操作...但是必须将过程硬连接到视图中有点臭.我希望 URL 顺序决定首先选择什么以及它交给什么.
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.
推荐答案
这当然是视图逻辑;所有 urls.py 用于匹配 URL 模式,而不是执行验证.您可以使用 Http404
处理这个异常.
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})
或者,您可以找到 <代码>get_object_or_404 或 get_list_or_404
方法,将其缩短一点.
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),
}
这篇关于引发 404 并继续 URL 链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!