Home > Backend Development > Python Tutorial > How to pass parameters in Django URL

How to pass parameters in Django URL

高洛峰
Release: 2017-02-27 16:54:40
Original
2162 people have browsed it

1 No parameters

The configuration URL and its view are as follows:

(r'^hello/$', hello)
 
def hello(request):
  return HttpResponse("Hello World")
Copy after login

Visit http://127.0.0.1 :8000/hello, the output result is "Hello World"

2 Pass a parameter
Configure the URL and its view as follows, specify a parameter in the URL through regular expression:

(r'^plist/(.+)/$', helloParam)
 
def helloParam(request,param1):
  return HttpResponse("The param is : " + param1)
Copy after login

Visit http://127.0.0.1:8000/plist/china, the output result is "The param is : china"

3 Pass multiple parameters
Refer to Chapter In the second case, take passing two parameters as an example. The configuration URL and its view are as follows. Two parameters are specified in the URL through regular expressions:

(r'^plist/p1(\w+)p2(.+)/$', helloParams)
 
def helloParams(request,param1,param2):
  return HttpResponse("p1 = " + param1 + "; p2 = " + param2)
Copy after login

Access http: //127.0.0.1:8000/plist/p1chinap22012/The output is "p1 = china; p2 = 2012"

It can be seen from here that the parameters of the view are based on the regular expression of the URL, matched in order and automatically Assigned. Although this can achieve the transfer of any number of parameters, it is not flexible enough. The URL looks confusing, and because it is a regular match, it is error-prone in some cases.

4 Pass parameters through the traditional "?"

For example, http://127.0.0.1:8000/plist/?p1=china&p2=2012, after the '?' in the url, it means passing Parameters, two parameters p1 and p2 are passed here.

By passing parameters in this way, problems caused by regular matching errors will not occur. In Django, the parsing of such parameters is obtained through the request.GET.get method.

The configuration URL and its view are as follows:

(r'^plist/$', helloParams1)
 
def helloParams(request):
  p1 = request.GET.get('p1')
  p2 = request.GET.get('p2')
  return HttpResponse("p1 = " + p1 + "; p2 = " + p2)
Copy after login

The output result is "p1 = china; p2 = 2012"

For more articles related to the method of passing parameters in Django URL, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template