run_the_race
run_the_race

Reputation: 2318

Django get url variables within get_context data?

Say I have a url likes this

    path(
        'foo/<int:foo_id>/edit/',
        views.FooView.as_view(),
        name='foo',
    ),

and a view likes this:

    def get(self, request, foo_id):

I find a common idiom is getting the URL variable foo_id into the context.

The only thing context has access to be default is request. I tried checking request and request.GET and could not see anything.

Is there a better way than:

Upvotes: 2

Views: 728

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

The url parameters are stored in the .kwargs of the view. You thus can access and render these with:

{{ view.kwargs.foo_id }}

There is a reference with the name view that is passed which is the View object that is constructed when handling a request. We thus access the .kwargs attribute of that View object, and in the kwargs, we look for kwargs['foo_id'].

A peculiarity in Django is that a TemplateView [Django-doc] passes all it kwargs items as context data, if your view is thus a TemplateView, then you can render this with

<!-- only a TemplateView -->
{{ foo_id }}

Upvotes: 4

Related Questions