具有多个 URL 模式和可选参数的相同视图

Same view with multiple URL patterns and optional arguments

我正在尝试设计 URLconf 文件,其中一个视图接受两个可选参数:dateaccount_uuid

views.py:

@login_required
def dashboard(request, date=None, account_uuid=None):
    # some unrelated code...

urls.py:

urlpatterns = patterns(
    'app.views',
    url(r'^dashboard$',
        'dashboard',
        name='dashboard'),
    #WHAT HERE??
)

用户可以访问包含一个或两个参数的 url。

没有参数:

http://example.com/dashboard

只有日期(ddmmyyy 格式)应该如下所示:

http://example.com/dashboard/01042015

仅使用帐户 UUID:

http://example.com/dashboard/e1c0b81e-2332-4e5d-bc0a-895bd0dbd658

日期和账户uuid:

http://example.com/dashboard/01042015/e1c0b81e-2332-4e5d-bc0a-895bd0dbd658

我应该如何设计我的 URLconf?它应该易于阅读和快速。

谢谢!

使用多个模式可能是实现此目的的最简单方法:

urlpatterns = patterns('app.views',
    url(r'^dashboard$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<date>[\d]{8})/$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<account_uid>[\da-zA-Z-]{36})/$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<date>[\d]{8})/(?P<account_uid>[\da-z-]{36})/$', 'dashboard', name='dashboard'),
)