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

相关文章

python编写简单端口扫描器

python编写简单端口扫描器

本文实例为大家分享了python编写简单端口扫描器的具体代码,供大家参考,具体内容如下 直接放代码 此代码只支持扫描域名,要扫描IP请自己修改 from socket import...

PyCharm+PySpark远程调试的环境配置的方法

PyCharm+PySpark远程调试的环境配置的方法

前言:前两天准备用 Python 在 Spark 上处理量几十G的数据,熟料在利用PyCharm进行PySpark远程调试时掉入深坑,特写此博文以帮助同样深处坑中的bigdata&mac...

Django与JS交互的示例代码

Django与JS交互的示例代码

应用一:有时候我们想把一个 list 或者 dict 传递给 javascript,处理后显示到网页上,比如要用 js 进行可视化的数据。 请注意:如果是不处理,直接显示在网页上,用Dj...

Python编程argparse入门浅析

Python编程argparse入门浅析

本文研究的主要是Python编程argparse的相关内容,具体介绍如下。 #aaa.py #version 3.5 import os #这句是没用了,不知道为什么markd...

浅谈Python类里的__init__方法函数,Python类的构造函数

如果某类里没有__init__方法函数,通过类名字创建的实例对象为空,切没有初始化;如果有此方法函数,通常作为类的第一个方法函数,有点像C++等语言里的构造函数。 class Ca:...