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

yipeiwu_com6年前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设计】。

相关文章

python3.6中@property装饰器的使用方法示例

本文实例讲述了python3.6中@property装饰器的使用方法。分享给大家供大家参考,具体如下: 1、@property装饰器的使用场景简单记录如下: 负责把一个方法变成属性...

Python实现快速计算词频功能示例

本文实例讲述了Python实现快速计算词频功能。分享给大家供大家参考,具体如下: 这几天看到一位同事的代码,方法如下: def cut_word(body): temp_dict...

Python后台开发Django会话控制的实现

页面跳转 页面跳转的url中必须在最后会自动添加【\】,所以在urls.py的路由表中需要对应添加【\】 from django.shortcuts import redirect...

Python闭包思想与用法浅析

本文实例讲述了Python闭包思想与用法。分享给大家供大家参考,具体如下: 浅谈 python 的闭包思想 首先 python的闭包使用方法是:在方法A内添加方法B,然后return 方...

python使用turtle绘制分形树

python使用turtle绘制分形树

由于分形树具有对称性,自相似性,所以我们可以用递归来完成绘制。只要确定开始树枝长、每层树枝的减短长度和树枝分叉的角度,我们就可以把分形树画出来啦!! 代码如下: # -*- co...