Search code examples
djangodjango-viewsdjango-forms

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:

  • Manually adding url variables to the context_data after get_context_data()
  • or passing it into get_context_data from a custom call from get? (ugly because class based views expect the same get_context_data signature)

Solution

  • 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 }}