网络编程
位置:首页>> 网络编程>> Python编程>> Django urls.py重构及参数传递详解

Django urls.py重构及参数传递详解

作者:站在两个世界的边缘  发布时间:2022-10-05 14:20:53 

标签:django,urls.py,重构,参数,传递

1. 内部重构#

Django urls.py重构及参数传递详解

2. 外部重构#

website/blog/urls.py

Django urls.py重构及参数传递详解

website/website/urls.py

Django urls.py重构及参数传递详解

3. 两种参数处理方式 #

1. blog/index/?id=1234&name=bikmin#

#urls.py


url(r'^blog/index/$','get_id_name')

#views.py


from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request):
 html = loader.get_template("index.html")
 id = request.GET.get("id")
 name = request.GET.get("name")
 context = Context({"id":id,"name":name})
 return HttpResponse(html.render(context))

#index.html


<body>
 <li>id:{{ id }}</li>
 <li>name:{{ name }}</li>
</body>

效果如下

Django urls.py重构及参数传递详解

2. blog/index/1234/bikmin#

#urls.py


url(r'^blog/index/(\d{4})/(\w+)/$','blog.views.get_id_name')

#views.py


from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request,p1,p2):
 html = loader.get_template("index.html")
 context = Context({"id":p1,"name":p2})
 return HttpResponse(html.render(context))

#index.html


<body>
 <li>id:{{ id }}</li>
 <li>name:{{ name }}</li>
</body>

效果如下:

Django urls.py重构及参数传递详解

3.blog/index/1234/bikmin (和-2不一样的在于views.py,接收的参数名是限定的)#

#urls.py


#限定id,name参数名
url(r'blog/index/(?P<id>\d{4})/(?P<name>\w+)/$','get_id_name')

#views.py


from django.http import HttpResponse
from django.template import loader,Context

def get_id_name(request,id,name):
 html = loader.get_template("index.html")
 context = Context({"id":id,"name":name})
 return HttpResponse(html.render(context))

#index.html


<body>
 <li>id:{{ id }}</li>
 <li>name:{{ name }}</li>
</body>

效果如下

Django urls.py重构及参数传递详解

来源:https://www.cnblogs.com/wongbingming/p/6900593.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com