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

yipeiwu_com5年前Python基础

1. 内部重构#

2. 外部重构#

website/blog/urls.py

website/website/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>

效果如下

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>

效果如下:

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>

效果如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

tensorflow中next_batch的具体使用

本文介绍了tensorflow中next_batch的具体使用,分享给大家,具体如下: 此处给出了几种不同的next_batch方法,该文章只是做出代码片段的解释,以备以后查看:...

对python 通过ssh访问数据库的实例详解

通常,为了安全性,数据库只允许通过ssh来访问。例如:mysql数据库放在服务器A上,只允许数据库B来访问,这时,我们需要用机器C去访问数据库,就需要用C通过ssh连接B,再访问A。 通...

python中的迭代和可迭代对象代码示例

什么是迭代(iteration)呢? 给定一个list或者tuple,通过for循环来遍历这个list或者tuple、这种遍历就是迭代(iteration)。只要是可迭代的对象都可以进行...

python画微信表情符的实例代码

python画微信表情符的实例代码

#@project = facepalm #@file = main #@author = Maoliang Ran #@create_time = 2018/8/28 22:...

python运行时间的几种方法

最早见过手写的,类似于下面这种: import datetime def time_1(): begin = datetime.datetime.now() sum =...