dease
dease

Reputation: 3076

Same view with multiple URL patterns and optional arguments

I am trying to design URLconf file, where one of the views accepts two optional parameters: date and account_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??
)

user may visit url which contains one OR both parameters.

Without arguments:

http://example.com/dashboard

With date (ddmmyyy format) only should look like:

http://example.com/dashboard/01042015

With account UUID only:

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

Both date and account uuid:

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

How should I design my URLconf? It should be easly readable and fast.

Thanks!

Upvotes: 8

Views: 9591

Answers (1)

knbk
knbk

Reputation: 53669

Using multiple patterns is probably the easiest way to achieve this:

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'),
)

Upvotes: 14

Related Questions