0

刚开始使用 Django 并弄清楚 URL 调度程序。根据我在文档中看到的内容,以下正则表达式应该可以捕获news/story/2012/10/23/this-is-my-first-story

urlpatterns = patterns('news.views',
    url(r'^$', 'index'),
    url(r'^news/story/(?P<year>\d{4})/(?P<month>\d){2}/(?P<day>\d){2}/(?P<title_key>\w+)/$', 'story'),
)

但是,我收到以下错误...

使用 中定义的 URLconf mysite.urls,Django 按以下顺序尝试了这些 URL 模式:

  • ^polls/
  • ^news/
  • ^$
  • ^news/
  • ^news/story/(?P<year>\d)/(?P<month>\d)/(?P<day>\d)/(?P<title_key>\d)/$
  • ^admin/doc/
  • ^admin/

当前 URLnews/story/2012/10/23/this-is-my-first-story与其中任何一个都不匹配。

4

1 回答 1

4

首先,每个模式只接受一个数字。您需要将其修改为\d+或更适当的\d{4}foryear\d{2}for monthand day

其次,最后一个模式,fortitle_key设置为只接受数字(\d),如果你想要一个slug,你应该使用[\w-]+

于 2012-10-19T16:13:10.807 回答