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

相关文章

详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题解决

详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题解决

也许自己真的就是有手残的毛病,你说好端端的环境配置好了,自己还在那里瞎鼓捣,我最不想看到的就是在安装一个别的模块的时候,自动卸载了本地的其他模块,每每这个时候,满满的崩溃啊,今天就是一个...

numpy中矩阵合并的实例

python中科学计算包numpy中矩阵的合并,需要用到如下两个函数: 列合并:np.column_stack() ,其中函数参数为一个tuple 行合并:np.row_stack(),...

TensorFlow打印tensor值的实现方法

TensorFlow打印tensor值的实现方法

最近一直在用TF做CNN的图像分类,当softmax层得到预测结果后,我希望能够看到预测结果,以便和标签之间进行比较。特此补上,以便自己记忆。 我现在通过softmax层得到变量trai...

CentOS 7下Python 2.7升级至Python3.6.1的实战教程

CentOS 7下Python 2.7升级至Python3.6.1的实战教程

前言 大家应该都知道,Centos是目前最为流行的Linux服务器系统,其默认的Python 2.x,但是根据python社区的规划,在不久之后,整个社区将向Python3迁移,且将不在...

Python 通配符删除文件的实例

实例如下所示: # -*- coding: utf-8 -*- """ 使用通配符,获取所有文件,或进行操作。 """ import glob import os def files...