django URL传递参数总结

  • 无参数的情况

配URl及其视图如下

url(r^'hello',views.hello)

def hello(request):
    return HttpResponse('hello word!')
  • 传递一个参数

配置URL及其视图如下,url中通过正则指定一个参数

url(r^'hello/(.+)/$',views.hello)

def hello(request,paraml):
     return HttpResponse('the param is' + paraml)
#访问http://127.0.0.1:8000/hello/china,输出结果为”The param is : china”
  • 传递多个参数(参照第二个种情况)

以传递两个参数为例,配置URL及其视图如下,URL中通过正则指定两个参数

url(r'^hello/p1(\w+)p2(.+)/$', views.hello)

def hello(request,param1,param2):
    return HttpResponse(p1 = param1,p2=param2)
#访问http://127.0.0.1:8000/hello/p1chinap22012/ 输出为”p1 = china; p2 = 2012″    
  • 通过传统的来传递参数(例如,http://127.0.0.1:8000/plist/?p1=china&p2=2012,url中‘?’之后表示传递的参数,这里传递了p1和p2两个参数。通过这样的方式传递参数,就不会出现因为正则匹配错误而导致的问题了。在Django中,此类参数的解析是通过request.GET.get方法获取的)

配置URL及其视图如下



def helloParams(request):
    p1 = request.GET.get('p1')
    p2 = request.GET.get('p2')
    return HttpResponse("p1 = " + p1 + "; p2 = " + p2)

猜你喜欢

转载自blog.csdn.net/qq_40861391/article/details/80134268
今日推荐