Reputation: 8774
I'm building a web app that displays TV Shows
and Episodes
. All my urls are geared towards TV Shows being the top level concept:
I've gotten interest from Networks
for consolidated pages with their shows as subdirectories
I'll need to support both, and obviously I dont want to repeat all my non-network URL confs. Is there a simple way to do this?
Upvotes: 0
Views: 74
Reputation: 2623
How about something like this:
urlpatterns = [
path('<tv-show-name>', render_your_view, name='tv-show'),
path('<network-name>/<tv-show-name>', render_your_view, name='network'),
]
So no matter if the requested URL is on a tv-show level or network-level, it triggers the according view(s).
Upvotes: 0
Reputation: 32304
You can include the same url patterns more than once. In your case, you can include them with and without the network name prefix
from django.urls import path, include
episode_patterns = [
path('<str:tv_show_name>/<str:episode_name>/', episode_detail),
path('<str:tv_show_name>/<str:episode_name>/cast/', episode_cast),
path('<str:tv_show_name>/<str:episode_name>/reviews/', episode_reviews),
]
urlpatterns = [
path('<str:network_name>/', include(episode_patterns)),
path('', include(episode_patterns)),
]
You may want to think about including "prefixes" in your paths so that they are more explicit. As it stands it could be fairly confusing as to which url is being matched
from django.urls import path, include
episode_patterns = [
path('show/<str:tv_show_name>/episode/<str:episode_name>/', episode_detail),
path('show/<str:tv_show_name>/episode/<str:episode_name>/cast/', episode_cast),
path('show/<str:tv_show_name>/episode/<str:episode_name>/reviews/', episode_reviews),
]
urlpatterns = [
path('network/<str:network_name>/', include(episode_patterns)),
path('', include(episode_patterns)),
]
This would give you urls like
Upvotes: 2
Reputation: 2798
Iterate through your urlpatterns
list again after definition.
Then str.replace()
for the url and append to the existing list?
For keyword name=<your_url_name>
in url to remain unique, Add a prefix to separate network from tv.
Upvotes: 0