URL resolution in Django with two patterns

Viewed 83

There is a need to provide options to task and subtask in Django. where example task is abc_123 ,example subtask is xyz-987

example.com/abc_123/options
example.com/abc_123/xyz-987/options

My urls.py file

urlpatterns = [
    url(r'^/(?P<taskId>.+)/options$', views.AvailableOptions.as_view()),
    url(r'^/(?P<taskId>.+)/(?P<subtaskId>.+)/options$', views.AvailableOptions.as_view()),
]

It is working fine when only taskId is sent. When both task and subtaskId is sent. The pattern is taking abc_123/xyz-987 as taskId. I need url to be resolved as abc_123 and xyz-987 as taskId and subtaskId respectively

1 Answers

You should not match the slash, so we can work with a character group that matches all except the slash, so:

urlpatterns = [
    url(r'^/(?P<taskId>[^/]+)/options$', views.AvailableOptions.as_view()),
    url(r'^/(?P<taskId>[^/]+)/(?P<subtaskId>[^/]+)/options$', views.AvailableOptions.as_view()),
]

You might however want to use path(…) [Django-doc] with the <str:…> path converter, so:

urlpatterns = [
    path('<str:taskId>/options/', views.AvailableOptions.as_view()),
    path('<str:taskId>/<str:subpathId>/options/', views.AvailableOptions.as_view()),
]
Related