tags:

views:

77

answers:

2

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\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? Thanks!

+4  A: 

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.

Nathan
+3  A: 

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

lazerscience
Thanks for the answers. I get it now. No need to use re to cater for the params in urls.py. Just collect the params in the views using request.Get.get()
Ben