我想让我通过url传递的参数为可选。
url(r'^dashboard/forms/(\w+)|/create/$','dashboard_message_create'),
url(r'^dashboard/forms/(\w+)/delete/$', 'delete'),
使用“|”的问题是django无法区分上述2个网址。 我是django的新手。所以这方面的任何指针都非常有用。提前致谢
答案 0 :(得分:3)
您可以尝试将两者关联到同一视图
url(r'^dashboard/forms/create/$','dashboard_message_create'),
url(r'^dashboard/forms/(\w+)/create/$','dashboard_message_create'),
然后,确保dashboard_message_create
不带参数
def dashboard_message_create(request, name=None):
# Body
答案 1 :(得分:1)
你可以做得更好,使用完全重新超级大国(好吧,几乎超级,在urlpatterns中没有前瞻......):
url(r'^dashboard/forms/((?P<name>\w+)/)?create/$','dashboard_message_create'),
url(r'^dashboard/forms/(?P<name>\w+)/delete/$', 'delete'),
将命名参数添加到视图中并忽略未命名的参数:
def dashboard_message_create(request, name, *args, **kwargs):
pass
当name
令牌与空字符串匹配时,None
arg将为((?P<name>\w+)/)?
。