访问模板或中间件中的命名 URL 参数

编程入门 行业动态 更新时间:2024-10-19 22:40:14
本文介绍了访问模板或中间件中的命名 URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 url conf 中,我有几个 URL 具有相同的命名参数,user_id.是否可以在中间件中访问此参数 - 因此我可以将其一般传递给 context_data - 或在模板本身中?

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?

示例 URL conf 来说明问题:

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

推荐答案

如果你在模板中需要这些数据,只需覆盖你视图的 get_context_data 方法:

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

这篇关于访问模板或中间件中的命名 URL 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 10:24:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   模板   参数   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!