Django和查询字符串参数 [英] Django and query string parameters

查看:164
本文介绍了Django和查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个'get_item'视图,我如何编写URL的以下PHP类型的URL模式?

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

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



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



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



我的网址格式:

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

我的观点:

  def get_item(request):
id = request.GET.get('id',None)
xxxxxx
简单来说,如何在django中实现php的查询字符串参数的url模式的样式?

解决方案

使您的模式如下所示:

 (r'^ get_item / $' ,get_item)

在您的看法中:

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

虽然对于正常的细节视图等,你应该把id / slug url而不是在查询字符串中!使用get参数,例如。用于过滤列表视图,用于确定当前页面等。


Assuming I have a 'get_item' view, how do I write the URL pattern for the following php style of 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/bar as it is not practical)

Specifically, how do I make 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

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?

解决方案

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...

这篇关于Django和查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆