且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 可选 url 参数

更新时间:2023-09-04 23:16:10

There are several approaches.

One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional

Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.

urlpatterns = patterns('',
    url(r'^project_config/$', views.foo),
    url(r'^project_config/(?P<product>w+)/$', views.foo),
    url(r'^project_config/(?P<product>w+)/(?P<project_id>w+)/$', views.foo),
)

Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:

def foo(request, optional_parameter=''):
    # Your code goes here