Ways to pass parameters to the Django URL

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 Http://127.0.0.1:8000/hello with the output as "Hello World"

2 passing a parameter
Configure the URL and its view as follows, specifying a parameter in the URL via regular:

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

Access to Http://127.0.0.1:8000/plist/china with the output as "the Param Is:china"

3 Passing multiple parameters
In the second case, to pass two parameters as an example, configure the URL and its view as follows, specifying two parameters in the URL through a regular:

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

Access http://127.0.0.1:8000/plist/p1chinap22012/output as "P1 = China; P2 = 2012″

As can be seen from here, the parameters of the view are matched in order and automatically assigned according to the regular form of the URL. Although this allows for the delivery of any number of parameters, but is not flexible enough, the URL seems to be confusing, 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 '? ' It then represents the passed arguments, which pass the P1 and P2 two parameters.

By passing parameters in this way, there is no problem with regular matching errors. In Django, the parsing of such parameters is through 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 is "P1 = China; 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.