Question

In my url conf, I have several URL's which have the same named parameter, user_id. Is it possible to access this parameter either in a middleware - so I can generically pass it on to the context_data - or in the template itself?

Sample URL conf to illustrate the question:

url(r'^b/(?P<user_id>[0-9]+)/edit?$', user.edit.EditUser.as_view(), name='user_edit'),
url(r'^b/(?P<user_id>[0-9]+)/delete?$', user.delete.DeleteUser.as_view(), name='user_delete')
Was it helpful?

Solution

If you need this data in the template, just override your view's get_context_data method:

class MyView(View):
    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['user_id'] = self.kwargs.get('user_id')
        return context

OTHER TIPS

For class based views, the view is already available in the context, so you dont need to do anything on the view side. In the template, just do the following:

{{ view.kwargs.user_id }}

See this answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top