Access named URL parameter in Template or Middleware

痴心易碎 提交于 2020-07-29 12:15:17

问题


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')

回答1:


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



回答2:


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




回答3:


For function based views:

template

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

views.py

def myview(request, PARAM):
    ...

Django 2.2



来源:https://stackoverflow.com/questions/9587018/access-named-url-parameter-in-template-or-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!