A summary of the methods for Django URL passing parameters _python

Source: Internet
Author: User

1 NO parameter condition

The configuration URL and its view are as follows:

(R ' ^hello/$ ', hello)
 
def hello (Request): Return
  httpresponse ("Hello World")

Access to Http://127.0.0.1:8000/hello, output as "Hello World"

2 passing a parameter
The configuration URL and its view are as follows, and a parameter is specified in the URL by a regular:

(R ' ^plist/(. +)/$ ', Helloparam)
 
def helloparam (request,param1): Return
  httpresponse ("The Param is:" + param1)

Access Http://127.0.0.1:8000/plist/china, the output is "the Param Is:china"

3 Passing multiple parameters
Referring to the second case, to pass two parameters as an example, configure the URL and its view as follows, and specify two parameters in the URL by specifying:

(R ' ^plist/p1 (\w+) P2 (. +)/$ ', helloparams)
 
def helloparams (request,param1,param2): Return
  HttpResponse (" P1 = "+ param1 +"; P2 = "+ param2)

Visit http://127.0.0.1:8000/plist/p1chinap22012/
Output is "P1 ="; P2 = 2012″

As you can see from here, the parameters of the view are matched and automatically assigned according to the regular form of the URL. While this allows for the passing of any number of parameters, it is not flexible enough, the URL looks messy, and because it is a regular match, in some cases error prone.

4 through the traditional "?" Passing parameters

For example, in Http://127.0.0.1:8000/plist/?p1=china&p2=2012,url '? ' After that, the passed arguments are passed, p1 and P2 two parameters.

By passing parameters in such a way, there is no problem caused by a regular match error. In Django, the parsing of such parameters is through the request. Obtained by the 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)

The output result is "P1 ="; P2 = 2012″

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.