Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 894
dease Avatar asked Apr 01 '15 17:04

dease


1 Answers

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'),
)
like image 158
knbk Avatar answered Nov 14 '22 23:11

knbk