Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access named URL parameter in Template or Middleware

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')
like image 889
Sjaak Trekhaak Avatar asked Mar 06 '12 15:03

Sjaak Trekhaak


People also ask

Can I pass URL as query parameter?

URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more.

How does Django treat a request URL string?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

How do I accept query parameters in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.


2 Answers

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

like image 155
Anupam Avatar answered Oct 05 '22 23:10

Anupam


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
like image 39
Chris Pratt Avatar answered Oct 06 '22 00:10

Chris Pratt