Access named URL parameter in Template or Middleware
Asked Answered
P

3

10

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')
Piceous answered 6/3, 2012 at 15:47 Comment(0)
F
6

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
Factional answered 6/3, 2012 at 15:50 Comment(0)
T
14

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

Tunis answered 22/2, 2018 at 5:40 Comment(1)
This should be the accepted answer as this requires no additional code.Italianize
F
6

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
Factional answered 6/3, 2012 at 15:50 Comment(0)
T
1

For function based views:

template

{% url 'view' PARAM=request.resolver_match.kwargs.PARAM %}

views.py

def myview(request, PARAM):
    ...

Django 2.2

Teth answered 9/7, 2020 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.