NoReverseMatch和urls.py

时间:2014-05-20 20:12:38

标签: python django

每当我尝试使用gitpaste运行搜索时,我都会收到TemplateSyntaxError

<a href='{% url owner_pastes owner=result.object.owner.pk %}'>
      {{ result.object.owner }}
</a>

urls.py的布局如下:

from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import redirect_to

urlpatterns = patterns('saic.paste.views',
    url(r'^live/$', 'live_paste', name='live_paste'),
    url(r'^(?P<pk>\d+)/$', redirect_to, {'url': '/paste/%(pk)s/'}),
    url(r'^(?P<pk>\d+)/(?P<private_key>[a-zA-Z0-9]+)?/?$', redirect_to, {'url': '/paste/%(pk)s/%(private_key)s/'}),
    url(r'^owner/$', redirect_to, {'url': '/owner/all/'}),
    url(r'^owner/anonymous/', 'user_pastes', name='anon_pastes'),
    url(r'^owner/(?P<owner>.+)/', 'user_pastes', name='user_pastes'),
    url(r'^paste/(?P<pk>\d+)/adopt/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_adopt', name='paste_adopt'),
    url(r'^paste/(?P<pk>\d+)/embed/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_embed', name='paste_embed'),
    url(r'^paste/(?P<pk>\d+)/edit/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_edit', name='paste_edit'),
    url(r'^paste/(?P<pk>\d+)/fork/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_fork', name='paste_fork'),
    url(r'^paste/(?P<pk>\d+)/favorite/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_favorite', name='paste_favorite'),
    url(r'^paste/(?P<pk>\d+)/delete/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_delete', name='paste_delete'),
    url(r'^paste/(?P<pk>\d+)/raw/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_raw', name='paste_raw'),
    url(r'^commit/(?P<pk>.+)/adopt/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'commit_adopt', name='commit_adopt'),
    url(r'^commit/(?P<pk>.+)/download/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'commit_download', name='commit_download'),
    url(r'^paste/(?P<pk>\d+)/(?P<private_key>[a-zA-Z0-9]+)?/?$', 'paste_view', name='paste_view'),
    url(r'^users/$', 'users', name='users'),
    url(r'^favorites/$', 'favorites', name='favorites'),
    url(r'^accounts/login/$', 'login', name='login'),
    url(r'^accounts/logout/$', 'logout', name='logout'),
    url(r'^accounts/register/$', 'register', name='register'),
    url(r'^accounts/preference/$', 'preference', name='preference'),
    url(r'^accounts/timezone/$', 'set_timezone', name='set_timezone'),
    url(r'^$', 'paste', name='paste'),
)

通过阅读Django文档,似乎我需要owner的url模式。这是我得到的其余错误:

  

渲染时捕获NoReverseMatch:反向&#39; owner_pastes&#39;同   论证&#39;()&#39;和关键字参数&#39; {&#39;所有者&#39;:5}&#39;没找到。

看起来URL就在那里。有什么问题?

1 个答案:

答案 0 :(得分:1)

根据以下行,网址名称不是owner_pastes,而是user_pastes

 url(r'^owner/(?P<owner>.+)/', 'user_pastes', name='user_pastes'),

试试这个:

<a href='{% url user_pastes owner=result.object.owner.pk %}'>{{ result.object.owner }}</a>

旁注:小心,使用Django&gt; = 1.5,你需要用引号括起第一个参数(否则它被视为一个变量):

<a href='{% url "user_pastes" owner=result.object.owner.pk %}'>{{ result.object.owner }}</a>