【问题标题】:Django urls.py Regex Not Working Like I ExpectedDjango urls.py 正则表达式没有像我预期的那样工作
【发布时间】:2013-05-25 05:33:14
【问题描述】:

我想要这样的网址 --

/chart/2012
/chart/2009
/chart/1996

...每个 #, 是一年。所以我将此行添加到我的应用程序的 urls.py --

url(r'^chart/(?P<year>\d+)$',views.chart,name="chart"),

但是当我转到 URL 时它会返回 404。 \d+ 不应该将数字捕获到year 变量中吗?

(是的,我的 views.py 中确实定义了一个图表函数,并且当我不尝试使用变量时它可以工作)

更新:

这是完整的 urls.py --

from django.conf.urls import patterns,url
from musichart import views

urlpatterns = patterns('',
    url(r'^$', views.index, name="index"),
    url(r'^chart/(?P<year>\d+)$',views.chart,name="chart"),
)

这是我的意见.py --

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext, loader #Context
from musichart.models import Station,Song,Album,Related,Artist


def index(request):
    template = loader.get_template('chart/index.htm')
    context = RequestContext(request, {
        'title': "Here is the title",
        'testvar': "blah blah blah testing 1 2 3",
        'numero': 17,
    })
    return HttpResponse(template.render(context))


def chart(request, year):
    template = loader.get_template('chart/chart.htm')
    context = RequestContext(request, {
        'title': "Here is the title",
        'testvar': "blah blah blah testing 1 2 3",
        'numero': 17,
    })
    return HttpResponse(template.render(context))

如您所见,目前它只是简单的框架,只是在进行测试以确保在我继续之前完成所有事情。 404 页面显示 --

Using the URLconf defined in msite.urls, Django tried these URL patterns, in this order:
^admin/
^accounts/
^chart/ ^$ [name='index']
^chart/ ^chart/(?P<year>\d+)$ [name='chart']
^health/
The current URL, chart/2010, didn't match any of these.

【问题讨论】:

  • chart 函数是否采用year 参数?
  • 即使没有,他也不会收到 404 错误,因为 404 表示 URL 不匹配。
  • 404 给出了可以与实际 URL 匹配的 URL 列表。您能否发布 404 页面报告的实际 URL?
  • 你能在模板中显示用法吗?
  • 你能显示完整的网址定义吗?

标签: regex django django-views django-urls


【解决方案1】:

我的猜测是您已经在项目级(IE,根)urlconf 中包含“图表”URI 组件,因此再次包含它,应用程序的 urlconf 会抛出解析器。基本上尝试从图表 url 中删除“chart/”,如下所示:

from django.conf.urls import patterns,url
from musichart import views

urlpatterns = patterns('',
    url(r'^$', views.index, name="index"),
    url(r'^(?P<year>\d+)$',views.chart,name="chart"),
)

此外,在包含根 urlconf 中的应用级 urlconf 时,请仔细检查“chart”之后是否没有尾随空格。

【讨论】:

  • 天哪,我不敢相信我没听懂。我一直在想这一定是一个正则表达式错误,因为我以前从来没有真正这样做过,我完全错过了真正的问题。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多