2011-11-19 104 views
1

我有以下击溃:相同的看法不同的URL

url(r'^future/programs/$', main.programs, {'period': 'future'}), 
url(r'^past/programs/$', main.programs, {'period': 'past'}), 

当我尝试显示模板链接,使用模板标签url这样

{% url main.views.main.programs %} 

我总是链接/past/programs/。当我尝试这样

{% url main.views.main.programs period="future" %} 

我得到一个错误:

Caught NoReverseMatch while rendering: Reverse for 'main.views.main.programs' with arguments '()' and keyword arguments '{'period': u'future'}' not found.

我怎样才能显示链接/future/programs/

+1

'main.views.main.candidates'是一个错字吗?要链接到'/ future/programs /',你应该调用'{%url main.views.programs period ='future'%}' –

+0

@pastylegs是的,这是一个错字。纠正。 – Deadly

回答

5

我想你可能想用一个单一的URL模式来解决:

url(r'^(?P(<period>[\w]+)/programs/$', main.views.programs), 

,并在您的视图:

def programs(request, period): 
    if period == 'future': 
     ... 
    elif period == 'past': 
     ... 

和模板:

{% url main.views.main.programs period="future" %} 

在你的方法,你错误的逆流正向流动,即the extra keyword arguments的URL与关键字arg conf为了匹配模式而传递的信息。

前者是额外的数据,您可以在匹配时将其传递给视图(即,当用户转到/ future/programs /,匹配模式并将period=future传递给视图),后者是用于匹配的URL的实际数据(即period=future传递给它试图匹配节选那些关键字参数的图案reverse()功能 - 你没有写清)

编辑:

一在你的url中使用更合适的模式将是这样的:

url(r'^(?P(<period>past|future)/programs/$', main.views.programs), 

其中选择只能是“过去”或“将来”。这是罚款传入的URL,但Django的reverse()功能(这是在网址模板标签中使用)不能处理的替代选择:

https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse

The main restriction at the moment is that the pattern cannot contain alternative choices using the vertical bar ("|") character.

+0

谢谢,它的作品。在我的应用程序中,我有'过去','未来'和'现在',但是'现在'它是索引页的别名。例如,URL'/ present/programs /'等于'/ programs /',如果使用这个URL'r'^(?P (| future | past | present))/ programs/$''我有一个'/ programs /'链接的问题,因为路由只匹配'//程序/' – Deadly

2

我宁愿分配给每个URL一个名字:

url(r'^future/programs/$', main.programs, 
          {'period': 'future'}, 
          name='future_programs'), 
url(r'^past/programs/$', main.programs, 
         {'period': 'past'}, 
         name='past_programs'), 

,并显示在你的模板的链接:

Past programs: {% url past_programs %} 
Future programs: {% url future_programs %} 

我认为这个解决方案更好,因为如果你只有两个选择,你可以忘记传递参数并验证它们。

现在,如果这两个选项(未来,过去)可以增长到更多,另一种解决方案会更好,但我认为情况并非如此。

相关问题