Python Django 和查询字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3711349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:28  来源:igfitidea点击:

Django and query string parameters

pythondjango

提问by Ben

Assuming I have a 'get_item' view, how do I write the URL pattern for the following php style of URL?

假设我有一个“get_item”视图,我如何为以下 php 样式的 URL 编写 URL 模式?

http://example.com/get_item/?id=2&type=foo&color=bar

(I am not using the standard 'nice' type of URL ie: http://example.com/get_item/2/foo/baras it is not practical)

(我没有使用标准的“好”类型的 URL,即:http://example.com/get_item/2/foo/bar因为它不实用)

Specifically, how do I make the view respond when the user types the above in a browser, and how do I collect the parameters and use it in my view?

具体来说,当用户在浏览器中键入上述内容时,如何使视图响应,以及如何收集参数并在我的视图中使用它?

I tried to at least get the id part right but to no avail. The view won't run when I type this in my browser http://example.com/get_item?id=2

我试图至少让 id 部分正确但无济于事。当我在浏览器中输入时,视图不会运行http://example.com/get_item?id=2

My url pattern:

我的网址模式:

(r'^get_item/id(?P<id>\d+)$', get_item)

My view:

我的看法:

def get_item(request):
    id = request.GET.get('id', None)
    xxxxxx

In short, how do I implement Php's style of url pattern with query string parameters in django?

简而言之,如何在 django 中使用查询字符串参数实现 Php 样式的 url 模式?

回答by Nathan

You just need to change your url pattern to:

您只需要将您的网址模式更改为:

(r'^get_item/$', get_item)

And your view code will work. In Django the url pattern matching is used for the actual path not the querystring.

您的视图代码将起作用。在 Django 中,url 模式匹配用于实际路径而不是查询字符串。

回答by Bernhard Vallant

Make your pattern like this:

像这样制作你的图案:

(r'^get_item/$', get_item)

And in your view:

在你看来:

def get_item(request):
    id = int(request.GET.get('id'))
    type = request.GET.get('type', 'default')

Though for normal detail views etc. you should put the id/slug in the url and not in the query string! Use the get parameters eg. for filtering a list view, for determining the current page etc...

尽管对于普通的详细视图等,您应该将 id/slug 放在 url 中,而不是在查询字符串中!使用获取参数,例如。用于过滤列表视图,用于确定当前页面等...

回答by Alok Choudhary

See this pattern

看到这个模式

url(r'^get_item$', get_item)

And your view will look like

你的观点看起来像

def get_item(request):
    id = int(request.Get.get('id'))