0

我想要这样的网址——

/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"),
)

这是我的views.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.
4

1 回答 1

1

我的猜测是你已经在项目级(IE,root)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 时,请仔细检查“图表”之后是否没有尾随空格。

于 2013-05-29T20:54:37.520 回答