Antonio
Antonio

Reputation: 832

Django urls.py: passing dynamic url parameter into include()

I found in Django docs (https://docs.djangoproject.com/en/3.0/topics/http/urls/#passing-extra-options-to-include) that I can pass any constant into include() statement. Here in docs' example we are passing blog_id=3.

from django.urls import include, path

urlpatterns = [
    path('blog/', include('inner'), {'blog_id': 3}),
]

But what if I want to pass dynamic url parameter into include()? I mean something like this:

from django.urls import include, path

urlpatterns = [
    path('blog/<int:blog_id>/', include('inner'), {'blog_id': ???}),
]

Is it possible?

Upvotes: 1

Views: 186

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You do not specify the kwargs, so you write:

from django.urls import include, path

urlpatterns = [
    # no { 'blog_id': … }
    path('blog/<int:blog_id>/', include('inner')),
]

The url parameter will be passed to the kwargs of the included views.

This is to some extent discussed in the documentation on Including other URLconfs where it says:

(…) For example, consider this URLconf:

from django.urls import path
from . import views

urlpatterns = [
    path('<page_slug>-<page_id>/history/', views.history),
    path('<page_slug>-<page_id>/edit/', views.edit),
    path('<page_slug>-<page_id>/discuss/', views.discuss),
    path('<page_slug>-<page_id>/permissions/', views.permissions),
]

We can improve this by stating the common path prefix only once and grouping the suffixes that differ:

from django.urls import include, path
from . import views

urlpatterns = [
    path('<page_slug>-<page_id>/', include([
        path('history/', views.history),
        path('edit/', views.edit),
        path('discuss/', views.discuss),
        path('permissions/', views.permissions),
    ])),
]

Upvotes: 1

Related Questions