1

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?

1
  • You omit the blog_id. It will simply be included in the kwargs of the included urls. Commented May 10, 2020 at 10:27

1 Answer 1

1

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),
    ])),
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.