简体   繁体   English

如何将变量从url传递到Django中的视图?

[英]How to pass a variable from the url to a view in django?

Simple question. 简单的问题。

How can I pass a variable from the URL to the view? 如何将变量从URL传递到视图? I'm following the Date Example . 我正在跟踪Date示例

My view needs to arguments: 我的观点需要争论:

def hours_ahead(request, offset):

My url.py has this" 我的url.py有这个”

(r'^plus/\d{1,2}/$', hours_ahead),

I know I need to pass another argument through but I don't know how to get the number from the URL string (ie 'time/plus/ 4 /'. Something like this? 我知道我需要传递另一个参数,但是我不知道如何从URL字符串中获取数字(即'time / plus / 4 /'。类似这样的东西吗?

(r'^plus/\d{1,2}/$', hours_ahead, offset=??),

您可以在正则表达式中使用命名组

(r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),

From chapter 3 of the django book : 在django书籍的第3章中

Now that we've designated a wildcard for the URL, we need a way of passing that wildcard data to the view function, so that we can use a single view function for any arbitrary hour offset. 现在,我们已经为URL指定了通配符,我们需要一种将通配符数据传递给view函数的方法,以便可以将单个view函数用于任意小时偏移量。 We do this by placing parentheses around the data in the URLpattern that we want to save. 我们通过在要保存的URL模式中的数据周围放置括号来做到这一点。 In the case of our example, we want to save whatever number was entered in the URL, so let's put parentheses around the \\d{1,2}, like this: 在我们的示例中,我们想保存在URL中输入的任何数字,因此让括号放在\\ d {1,2}周围,如下所示:

(r'^time/plus/(\d{1,2})/$', hours_ahead),

If you're familiar with regular expressions, you'll be right at home here; 如果您熟悉正则表达式,就可以在这里找到家。 we're using parentheses to capture data from the matched text. 我们使用括号从匹配的文本中捕获数据。

I am not sure I understand your question clearly. 我不确定我是否清楚理解您的问题。 Here is my shot at answering based on what I understood. 这是我根据自己的理解回答的镜头。

Adding a named regex group to your URL configuration should help: 命名的正则表达式组添加到您的URL配置应该会有所帮助:

(r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),

This will let you keep the existing view: 这将使您保留现有视图:

def hours_ahead(request, offset):
    ...

you can add additional variables like this: 您可以添加其他变量,如下所示:

(r'^plus/\d{1,2}/$', {'hours' : 5},  hours_ahead),

Best regards! 最好的祝福!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM