Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get URL parameters in a Django view?

Tags:

django

Suppose I have a url that has php style parameters, that is:

 http://example.com/blah?param1=val1&param2=val2 

and I want to place their values into the generated HTML of the template.

How do I achieve this?

like image 727
EpsilonVector Avatar asked Jun 03 '11 09:06

EpsilonVector


People also ask

How do I get all query 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.

How does Django URL parameters and query strings work?

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!

How do I find parameters in URL?

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.


2 Answers

{{request.GET.param1}} in the template. (Using RequestContext)

request.GET.get('param1', None) in the view.

like image 93
JamesO Avatar answered Sep 20 '22 00:09

JamesO


{{ request.resolver_match.kwargs.argument }} 

for function arguments passed to the view as:

def myview(request, argument): 

Tested on Django 1.9.