P1,导学(6.30) flask 短小精悍 Django 重武器,有各种中间件
P2,django安装(7.2) pip install django
P3,创建项目(终端命令)(7.2) 打开终端,进入目录(项目放的位置) django-admin startproject (项目名称)
P4,创建项目(pycharm专业版) 利用pycharm创建项目选择Location时 不要放在python自带的解释器目录,以后删除项目可能把解释器一起删除了
P5,对比两种创建方式(7.3) 命令行,创建的项目是标准的 pycharm,会自动添加 setting.py TEMPLATES = [ ‘DIRS’ : [os.path.join(BASE_DIR, ‘templates’)] ] }
P6,默认文件介绍(7.3) -mysite manage.py -mysite init.py 【】 settings.py 【项目配置(连接数据库)(创建app)】 urls.py 【url和函数的对应关系】 asgi.py 【接受网络请求(异步请求)】【不要动】Django3还不太成熟 wsgi.py 【接受网络请求(同步请求)】【不要动】
P7,app的创建和说明(7.3) -项目 -app1,用户管理【表,函数,html,css】 -app2,订单管理【表,函数,html,css】 -app1,后台管理【表,函数,html,css】 -app1,API管理【表,函数,html,css】 创建方式:python manage.py startapp app01 -app01 init.py admin.py 【(固定不动)django默认提供的admin后台管理,常用于添加数据】 apps.py 【(固定不动)app启动类】 -migraions.py 【(固定不动)数据库变更记录】 init.py models.py 【(重要)对数据库进行操作,封装的类,ORM】 test.py 【(固定不动)单元测试】 views.py 【(重要)对应函数】
P8,启动运行Django(7.3) 快速上手步骤 -app注册, app.py->class App01Config->name setting.py->INSTALLED_APPS[‘app01.apps.App01Config’,] -url和视图函数的对应关系 url.py urlpatterns = [ path(‘admin/’, admin.site.urls), path(‘index/’, views.index) -app01 views.py def index(request): return HttpResponse(“Hello, world”) 启动方式 密码行 python mange.py runserver 127.0.0.1:8000 Pycharm 绿色启动键
P9,模板和静态文件(7.3) views.py def user_list(request): return render(request, ‘user_list.html’) render查找顺序:按注册app顺序查找所有,默认不去根目录下找(不配置setting.py的话) 配置DIR:优先去根目录找 模板 -app01 -templates xx.html 静态文件 -app01 -static(新建) -css -img -js -plugins 引用静态文件 {% load static %} 【html文件顶端】 【绝对路径】以后改了静态文件位置不方便 【相对路径】去setting.py->STATIC_URL = ‘/static/’
P10,Django模板语法(7.3,7.4) 模板逻辑: render读取含有模板语法的html 内部进行渲染(模板语言执行并完成替换数据) 得到最终的html 将最终的html发给用户浏览器 views.py
def tpl(request):
name = "张三"
roles = ['管理员', 'CEO', '保安']
user_info = {
"name": "李四", "salary": 8000, "role": "CEO"
}
data_list = [
{"name": "李四1", "salary": 8000, "role": "CEO"},
{"name": "李四2", "salary": 8000, "role": "CEO"},
{"name": "李四3", "salary": 8000, "role": "CEO"},
{"name": "李四4", "salary": 8000, "role": "CEO"},
]
return render(request, 'tpl.html', {'n1': name, 'n2': roles, 'n3': user_info, 'n4': data_list} )
tpl.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板</title>
</head>
<body>
<h1>模板</h1>
<div>{{ n1 }}</div>
<div>{{ n2 }}</div>
<div>{{ n2.0 }}</div>
<div>{{ n2.1 }}</div>
<h1>循环</h1>
<div>
{% for item in n2 %}
<span>{{ item }}</span>
{% endfor %}
</div>
<h1>字典</h1>
<div>{{ n3 }}</div>
<div>{{ n3.name }}</div>
<div>{{ n3.salary }}</div>
<div>{{ n3.role }}</div>
<ul>
{% for item in n3 %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% for item in n3.keys %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% for item in n3.items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% for k,v in n3.items %}
<li>{{ k }} = {{ v }}</li>
{% endfor %}
</ul>
<h1>列表里面套字典</h1>
{{ n4.1 }}
{{ n4.1.name }}
{{ n4.1.role }}
{% for item in n4 %}
<div>{{ item.name }}{{ item.salary }}</div>
{% endfor %}
<h1>嵌套条件语句</h1>
{% if n1 == "李四" %}
<p>是李四</p>
{% elif n1 == "张三" %}
<p>是张三</p>
{% else %}
<p>不是李四,也不是张三</p>
{% endif %}
</body>
</html>
P11,请求和响应(7.4,7.5)
def qingqiu(request):
print(request.method)
print(request.GET)
print(request.POST)
return HttpResponse("ok")
登录页面获取传递数实例:
def login(request):
if request.method == "GET":
return render(request, 'login.html')
else:
print(request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
print(password)
if username == "123" and password == "qwe":
return HttpResponse("登录成功")
else:
return render(request, "login.html", {"error_msg": "用户名或密码错误"})
<form method="POST" action="/login/">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名"/>
<input type="password" name="password" placeholder="密码"/>
<input type="submit" value="提交"/>
<span style="color: red">{{ error_msg }}</span>
</form>
P12,ORM连接MySQL的模块(7.6) Django为了开发操作数据库更简单,内部提供了ORM框架 代码—>ORM(翻译sql语句)—>pymysql/MySQLdb/mysqlclient 安装:pip install pymysql/mysqlclient 如果windows安装报错,百度mysqlclient wheel安装包
P13,ORM创建数据库(7.6) ORM的主要链两个功能: 创建、修改、删除表(不用写原始sql语句)(不能创建数据库) 操作数据库 自带工具创建数据库(!!!这里一定要记得用命令语句创建,界面新增会默认latin1字符格式,不支持中文) create database xxx DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
P14,ORM连接数据库(7.6) 在setting.py里修改配置 默认是sqlite3文件数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': '',
'PORT': '',
}
}
P15,ORM类创建表(7.6) models.py
class UserInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
"""
相当于翻译成:
create talbe app01_userinfo(
id bigint auto_increment primary key,
name varchar(32),
password varchar(64),
age int
"""
执行语句: python manage.py makemigrations python manage.py migrate
P16,ORM创建和修改表结构(7.6) 删除直接注释表和字段即可 新增列原来表中可能有数据,三个应对方法 手动填充默认值(default=1) 设置默认值为空(null=True, blank=True) 生成时选择1,2选项
P17,ORM增删改查(7.7) models.py
views.py
from app01.models import Department, UserInfo
def orm(request):
UserInfo.objects.all().update(password=999)
UserInfo.objects.filter(name="张三").update(password=999)
return HttpResponse("数据库操作成功")
P18,案例:用户管理(7.7) 1.展示用户信息 url链接 函数 获取用户信息 HTML渲染 2.添加用户 url 函数 GET请求看到界面 POST请求提交写入数据库 3.删除用户 url 函数 获取要删除的参数 操作数据库 views.py
def user_info_list(request):
data_list = UserInfo.objects.all()
print(data_list)
return render(request, "user_info_list.html", {'data_list': data_list})
def user_info_add(request):
if request.method == "GET":
return render(request, 'user_info_add.html' )
else:
name = request.POST.get("username")
password = request.POST.get("password")
age = request.POST.get("age")
UserInfo.objects.create(name=name, password=password, age=age)
return redirect("/user_info_list/")
def user_info_del(request):
nid = request.GET.get("nid")
UserInfo.objects.filter(id=nid).delete()
return redirect('/user_info_list/')
user_info_list.html
<body>
<h1>用户列表</h1>
<a href="/user_info_add/">添加用户</a>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
<td>
<a href="/user_info_del?nid={{ obj.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
user_info_add.html
<body>
<h1>添加用户信息</h1>
<form method="POST" action="/user_info_add/">
{% csrf_token %}
<p><input type="text" name="username" placeholder="用户名"></p>
<p><input type="text" name="password" placeholder="密码"></p>
<p><input type="text" name="age" placeholder="年龄"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
P19,内容概要(7.8) 主题:员工管理系统(更完整、美化)
P20,创建项目和app Pycharm编辑器上面的Tool中的Run manage.py Task 相当于执行了manage.py,直接输入startapp app02_staff_management
P21,设置表结构的创建 models.py
from django.db import models
class Department(models.Model):
"""部门表"""
title = models.CharField(verbose_name="标题", max_length=32)
class UserInfo(models.Model):
"""员工表"""
name = models.CharField(verbose_name="姓名", max_length=16)
password = models.CharField(verbose_name="", max_length=64)
age = models.IntegerField(verbose_name="年龄")
account = models.DecimalField(verbose_name="账户余额", max_length=10, decimal_places=2, default=0)
create_time = models.DateTimeField(verbose_name="入职时间")
department = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE())
gender_choices = (
(1, "男"),
(2, "女"),
)
gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)
P22,生成数据库(7.9) python manage.py makemigrations python manage.py migrate
P23,部门列表展示(前端页面)(7.9) 以后项目需要的话可以直接套用,大小格式已经调好
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>部门管理</title>
<link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<style>
.navbar{
border-radius: 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
{# <div class="container-fluid">#}
<div class="container"> {# 居中#}
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">用户管理系统</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">登录</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户名XXX <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">个人资料</a></li>
<li><a href="#">我的信息</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">注销</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div>
<div class="container">
<div style="margin-bottom: 10px">
<a class="btn btn-success" href="#">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
新建部门
</a>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
部门列表
</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>销售部</td>
<td>
<a class="btn btn-primary btn-xs">编辑</a>
<a class="btn btn-danger btn-xs">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery-3.6.0.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</body>
</html>
P24,部门-数据库数据(7.10) 后端:views.py(获取数据传给前端)
def depart_list(request):
queryset = models.Department.objects.all()
return render(request, "depart_list.html", {'queryset': queryset})
前端循环展示信息
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}</th>
<td>{{ obj.title }}</td>
<td>
<a href="#" class="btn btn-primary btn-xs">编辑</a>
<a href="#" class="btn btn-danger btn-xs">删除</a>
</td>
</tr>
{% endfor %}
P25,部门-添加页面(7.10) 在新的界面打开要加上target
<a class="btn btn-success" href="/depart_add/" target="_blank">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
新建部门
</a>
!!!pycharm快捷键ctrl+alt+L可以吧拷过来的html代码自动对齐
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加部门</title>
<link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<style>
.navbar {
border-radius: 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
{# <div class="container-fluid">#}
<div class="container"> {# 居中#}
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">用户管理系统</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">登录</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">用户名XXX <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">个人资料</a></li>
<li><a href="#">我的信息</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">注销</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">新建部门</h3>
</div>
<div class="panel-body">
<form>
<div class="form-group">
<label>标题</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="title" placeholder="标题">
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery-3.6.0.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</body>
</html>
在这里插入代码片
P26,部门添加(7.10) 后端views.py
def depart_add(request):
if request.method == "GET":
return render(request, "depart_add.html")
else:
title = request.POST.get("title")
models.Department.objects.create(title=title)
return redirect('/depart_list/')
<form action="/depart_add/" method="POST">
{% csrf_token %}
<div class="form-group">
<label>标题</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="title" placeholder="标题">
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
P27,部门删除(7.10)
def depart_del(request):
nid = request.GET.get('nid')
models.Department.objects.filter(id=nid).delete()
return redirect('/depart_list/')
P28,部门编辑(7.10)
def depart_edit(request, nid):
if request.method == "GET":
row_obj = models.Department.objects.filter(id=nid).first()
return render(request, "depart_edit.html", {"department": row_obj})
else:
title = request.POST.get('title')
models.Department.objects.filter(id=nid).update(title=title)
return redirect('/depart_list/')
<form action="/depart_edit/{{ department.id }}/" method="POST">
{% csrf_token %}
<div class="form-group">
<label>标题</label>
<input value="{{ department.title }}" type="text" class="form-control" id="exampleInputEmail1" name="title" placeholder="标题">
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
P29,模板的继承(7.10)
<div>
<div class="container">
{% block content %}
{% endblock %}
</div>
</div>
{% extends 'layout.html' %}
{% block content %}
<h1>首页</h1>
{% endblock %}
如果只有某几个页面用到特殊的css,js,可以多写几个模板块
|