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?
We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.
Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).
re_path is a callable within the django. urls module of the Django project.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With