Django 路由系统URL 视图views
一.Django URL (路由系统)
URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表;你就是以这种方式告诉Django,对于这个URL调用这段代码,对于那个URL调用那段代码。
urlpatterns = [
url(正则表达式, views视图函数,参数,别名),
]
参数说明:
- 一个正则表达式字符串
- 一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串
- 可选的要传递给视图函数的默认参数(字典形式)
- 一个可选的name参数 html 里面加 "{% url 'name' %}"
Here’s a sample URLconf:

from django.conf.urls import url
from django.contrib import admin from app01 import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), #url(r'^articles/[0-9]{4}/$', views.year_archive), url(r'^articles/([0-9]{4})/$', views.year_archive), #no_named group url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]

Note:

#1 There’s no need to add a leading slash, because every URL has that. For
# example, it’s ^articles, not ^/articles. #2 A request to /articles/2005/03/ would match the third entry in the list.
# Django would call the function views.month_archive(request, '2005', '03'). #3 /articles/2005/3/ would not match any URL patterns #4 /articles/2003/ would match the first pattern in the list, not the second one #5 /articles/2003/03/03/ would match the final pattern. Django would call the
# functionviews.article_detail(request, '2003', '03', '03').

5.2 Named groups
The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.
In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern)
, where name
is the name of the group and pattern
is some pattern to match.
Here’s the above example URLconf, rewritten to use named groups:

import re ret=re.search('(?P<id>\d{3})/(?P<name>\w{3})','weeew34ttt123/ooo') print(ret.group())
print(ret.group('id'))
print(ret.group('name'))


from django.conf.urls import url from . import views urlpatterns = [
url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
url(r'^time_list/(?P<post_time>\d{4}/\d{1,2}/\d{1,2}/\d{1,3})$', views.time_list),
] # views.py
def time_list(request,post_time):
if request.method == "GET":
print(post_time.split("/"))
return HttpResponse(" ".join(post_time.split("/")))

This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments.
5.3 Passing extra options to view functions
URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.
The django.conf.urls.url()
function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.
For example:
from django.conf.urls import url
from . import views urlpatterns = [
url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),
]
In this example, for a request to /blog/2005/
, Django will call views.year_archive(request, year='2005',foo='bar')
.
This technique is used in the syndication framework to pass metadata and options to views.
Dealing with conflicts
It’s possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.
5.4 name param

urlpatterns = [
url(r'^index',views.index,name='bieming'),
url(r'^admin/', admin.site.urls),
# url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/([0-9]{4})/$', views.year_archive),
# url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
# url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
################### def index(req):
if req.method=='POST':
username=req.POST.get('username')
password=req.POST.get('password')
if username=='alex' and password=='123':
return HttpResponse("登陆成功") return render(req,'index.html') ##################### <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{# <form action="/index/" method="post">#}
<form action="{% url 'bieming' %}" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="submit">
</form>
</body>
</html> #######################

5.5 Including other URLconfs

#At any point, your urlpatterns can “include” other URLconf modules. This
#essentially “roots” a set of URLs below other ones. #For example, here’s an excerpt of the URLconf for the Django website itself.
#It includes a number of other URLconfs: from django.conf.urls import include, url urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls')),
]

二.视图函数路由的设置
创建好基本的目录后,如果你想访问user中的views的视图函数,先要进行一些设置。
为什么要设置?以及流程是怎样的?
因为用户在浏览器输入网站,发过来请求时,django会根据正则选出相应的视图,Django会把请求信息封装为一个
HttpRequest
对象,并作为视图的第一个参数传入。所以视图函数也必须定义一个形参,用来接受HttpRequest对象。视图必须返回一个HttpResponse
对象(或其子类对象),不能像Flask一样直接返回字符串!所以说,HttpRequest
请求对象由Django创建,HttpResponse
响应对象由开发人员创建。
(1)第一种方法:
在项目python包里的urls.py修改,直接指向user.views。
例如我们要访问127.0.0.1/user/index
项目python包的设置如下:
from user import views
urlpatterns = [
url(r'^admin/', admin.site.urls), # 默认有的,别动
url(r'^user/index$',views.index) # 添加这条
]
user.views的代码简单演示:
from django.http import HttpResponse def index(request): # 一定要接受一个参数,这个参数的类型是HttpRequest对象
return HttpResponse("hello,django") # 返回的必须是HttpRespones
但是一般不用这种方法。
(2)第二种方法: 推荐用这种方法
为了减轻项目下的urls.py文件的配置量,方便url的管理,会分别在项目的urls.py和app文件夹下的urls.py中进行配置。
例如我们也是要访问127.0.0.1/user/index
项目下的urls.py文件设置如下:
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/',include('user.urls'))
]
user文件夹下的urls.py文件设置如下(注意,这个文件需要自己创建):

from django.conf.urls import url
from user import views urlpatterns=[
url(r'^index$',views.index)
]

附:
设置流程图片示例:
设置路由时需要注意的一个点是:Django中定义路由时,通常习惯以斜线 / 结尾
注意:当用户访问不以斜线/结尾的相同路径时,Django会把用户重定向到以斜线/结尾的路径上,而不会返回404不存在,例如:
urlpatterns = [ url(r'^index/$', views.index, name='index'), ]
用户访问
index/
网址,均能访问到index视图。
CP https://www.cnblogs.com/chichung/p/9872766.html
https://www.cnblogs.com/yuanchenqi/articles/6083427.html
Django 路由系统URL 视图views的更多相关文章
- Django路由系统---url无命名分组
django重点之url无命名分组[参数有顺序要求] settigs.py:增加STATICFILES_DIRS静态资源路径配置,名称为创建的文件夹名称 'DIRS': [os.path.join(B ...
- Django路由系统-URL命名&URL反向解析
命名URL和URL反向解析 前言 起始样式,HTML中的href是写死的,不能更改,如下示例代码: # urls中 urlpatterns = [ url(r'^admin/', admin.site ...
- Python学习---Django路由系统【all】
Django URL (路由系统) Django URL (路由系统): URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL模式以及要为该URL模式调用的视图函数之间的映 ...
- Django 框架篇(四) : 视图(view)详解 以及 路由系统(url)
|--Django的View(视图) |-- CBV和FBV: |-- 给视图增加装饰器: |-- request对象: |-- response对象: |-- Django的路由系统(url): | ...
- Django(二)路由系统、视图、模板
大纲 一.内容概要: 二.上节回顾 三.Django 视图–views 1.获取用户多个数据及文件上传 2.FBV 和 CBV 3.装饰器 四.Django模板补充 - Django模板语言循 ...
- python第一百零五天 ---Django 基础 路由系统 URL 模板语言 ORM 操作
一 路由系统 URL 1 url(r'^index/',views.index) url(r'^home/', views.Home.as_view()) 2 url(r'^detail-(\d+). ...
- 【python】-- Django路由系统(网址关系映射)、视图、模板
Django路由系统(网址关系映射).视图.模板 一.路由系统(网址关系映射) 1.单一路由对应: 一个url对应一个视图函数(类) urls.py: url(r'^test', views.test ...
- django目录下的路由系统和视图函数
一.Django路由系统(url) 1.什么是路由系统 路由系统的本质是URL模式以及要为该URL模式调用的视图函数之间的一个映射表即不同的url路径对应的不同的函数,该路由系统是存放在全局配置文件u ...
- django路由系统之反向生成url
from niubin.service import v1 from django.urls import reverse from django.shortcuts import HttpRespo ...
随机推荐
- Explorer内存占用偶尔变高导致卡顿
症状: 打开 "这台电脑",加载缓慢.此时查看任务管理器,explorer内存可能飙升到几G.cpu也很高 创建和删除文件缓慢,删除单个文件也会出现进度条.此时查看任务管理器,会出 ...
- javascript闭包使用 分类: JavaScript 2015-05-01 11:34 652人阅读 评论(3) 收藏
之前看到一段代码,很是不能理解,然后就查找资料并且找网络上得大牛请教,最后弄懂了这段代码,然后就拿出来总结一下. 1.挖坑 先来看一段代码: var arrTest = []; for (var i ...
- Android 开发工具类 01_AppUtils
1.获取应用程序名称: 2.获取应用程序版本信息. import android.content.Context; import android.content.pm.PackageInfo; imp ...
- Spring Boot 的彩色日志
springboot的彩色日志灰常漂亮, 看起来也很舒服. 但是自定义的日志就是一纯白色的, 丑到不行. 所以就copy他的彩色日志来养眼: <!-- 彩色日志 --> <!-- 彩 ...
- 三篇文章了解 TiDB 技术内幕 - 说存储(转)
引言 数据库.操作系统和编译器并称为三大系统,可以说是整个计算机软件的基石.其中数据库更靠近应用层,是很多业务的支撑.这一领域经过了几十年的发展,不断的有新的进展. 很多人用过数据库,但是很少有人实现 ...
- 业务ID 生成策略
业务ID 生成策略,从技术上说,基本要借助一个集中式的引擎来帮忙实现. 为了扩大业务ID生成策略的并发问题,还有更为技巧性的提升. 先来介绍普遍的分布式ID生成策略: 1. 利用DB的自增主键 这里又 ...
- spark、hadoop集群添加节点
1.首先添加hdfs的节点,将安装包上传到服务器,设置好环境变量.配置文件按之前spark集群搭建的那里进行修改. 设置完成后,要对新节点新型格式化: # hdfs dfs namenode - ...
- 【JavaScript 从零开始】表达式和运算符(2)
in运算符 in运算符希望它的左操作数是一个字符串或可以转换为字符串,希望它的右操作数是一个对象. 如果右侧的对象拥有一个名为做操作数值的属性名,那么表达式返回true,例如: var point= ...
- 转载:sql用逗号连接多张表对应哪个join?
http://blog.csdn.net/huanghanqian/article/details/52847835 四种join的区别已老生常谈: INNER JOIN(也可简写为JOIN): 如果 ...
- EnyimMemcached(64位)使用实例
1.安装:http://www.cnblogs.com/dudu/archive/2009/07/19/1526669.html 2.使用 using Enyim.Caching.Configurat ...