Suppose I have a url that has php style parameters, that is:
http://example.com/blah?param1=val1¶m2=val2
and I want to place their values into the generated HTML of the template.
How do I achieve this?
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 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!
Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.
{{request.GET.param1}}
in the template. (Using RequestContext)
request.GET.get('param1', None)
in the view.
{{ request.resolver_match.kwargs.argument }}
for function arguments passed to the view as:
def myview(request, argument):
Tested on Django 1.9.
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