1 课程介绍
2 基本流程
3 urls基本讲解及view视图
目的:用时Django开发出一款运维管理系统CMDB
基本流程
Django是Python中遵循软件框架MVC模型的web框架。Django把改模型该为MVT 内容思路大概一致。
MVC模型
M Model 模型 和数据库交互
V View 视图 生成HTML页面
C Controller 控制 接受请求和处理 和M,V交互,并返回结果给浏览器
MVT模型
M Model 模型 和数据库交互 和MVC中M功能相同
T Template 模板 生成HTML页面 和MVC中V功能相同
V View 视图 接受请求和处理 和M,V交互,并返回结果给浏览器,和MVC中C功能相同
使用Django创建项目和应用后对应的目录
项目目录下结构
.
├── manage.py ##项目的管理文件
└── test1
├── __init__.py ##说明test1是Python包
├── settings.py ##项目的配置文件 指定使用的数据库
├── urls.py ##进行url路由配置 通过它来找对应的函数来处理用户url
└── wsgi.py ##web服务器和Django交互的入口
应用目录下结构
.
├── admin.py 网站后台管理文件
├── apps.py
├── __init__.py ##说明web目录是Python模块
├── migrations ##迁移文件目录 把models.py中类生成迁移文件(用于生成数据库对应的表)
│ └── __init__.py ##说明migrations目录是Python模块
├── models.py ##写数据库项目的内容
├── tests.py ##写测试代码文件 不重要
└── views.py ##定义处理请求的函数
URL配置
urls.py 用于IP路由的 默认格式是 url(正则表达式, 视图函数),
from web import views ##插入web包的views模块
urlpatterns = [
url(r'^login/$', views.login), ##以login结尾的url的请求 给views.py中login函数处理
]
view视图
from django.shortcuts import render,HttpResponse,redirect ##插入render,HttpResponse,redirect 模块
##定义login函数返回Hello World!
def login(request):
return HttpResponse('Hello Wrold!')
更改返回内容并通过template把内容返回到页面上给用户
def login(request):
if request.method == 'GET':
date = 'Hello World!'
mes = 'It is first project!'
return render(request,'login.html',locals()) ##把变量和login.html页面渲染在一起
locals() 等于 {'date':date,'mes':mes} 'date' ,'mes'是把值传给login.html上的模板变量{{ date }} {{ mes }}
def login(request):
if request.method == 'GET':
date = 'Hello World!'
mes = 'It is first project!'
return render(request,'login.html',{'date':date,'mes':mes})
template目录上login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h3> {{ date }} </h3>
<h4> {{ mes }} </h4>
</body>
</html>