Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - Django and query string parameters

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Django processes the query string automatically and makes its parameter/value pairs available to the view. No configuration required. The URL pattern refers to the base URL only, the query string is implicit.

For normal Django style, however, you should put the id/slug in the base URL and not in the query string! Use the query parameters eg. for filtering a list view, for determining the current page etc...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...