当前位置: 首页>后端>正文

py-django0

一 base

1-1

一.安装 django
1.pycharmFileSettingProject_py解决器(带有py安装路径)上安装django
Admin路径=C:\Users\admin\AppData\Local\Programs\Python\Python310\Scripts\django-admin.exe
2.pip3 install django  查找django-admin.exe的路径
3.如果方案有虚拟环境也可以安装在虚拟环境中 方案\venv\Scripts\django-admin.exe
0.
py解释器默认安装的位置 C:\Users\admin\AppData\Local\Programs\Python\Python310
py路径=C:\Users\admin\AppData\Local\Programs\Python\Python310\python.exe
存放数据C:\Users\admin\AppData\Roaming\Python\Python310
cmd:where python(本机安装python解释器并已加入环境变量) pip show django (django安装位置)
C:\Users\admin\AppData\Local\Programs\Python\Python310\Lib\site-packages\django
C:\Users\admin\AppData\Local\Programs\Python\Python310\Lib\site-packages\Django-4.1.dist-info

二.新建 django项目
(一) 新建项目方案
新建目录和CMD进入该目录 J:\common\pyproject\py2024_2
cmd: Admin路径 mysite (自动生成 mysite/mysite/5个py文件 mysite/manage.py)
pycharmFileOpen该目录(方案) J:\common\pyproject\py2024_2\mysite

wsgi=WebServerGatewayInterface同步接收网络请求
asgi=异步接收网络请求(技术不成熟)asynchronous

(二) 新建app包目录  #视图函数模块 可创建多个app包
(pycharm终端)PS J:\common\pyproject\py2024_2\mysite> (或者该目录下cmd)

C:\Users\admin\AppData\Local\Programs\Python\Python310\Scripts\django-admin.exe startapp app01
django-admin.exe startapp app02 ((如果py已加入环境变量 路径可简化)
django-admin startapp app03

(三) mysite\mysite\settings.py 注册app包  视图函数模块需要注册关联
1.app01/apps.py:  找到class App01Config(AppConfig)的类名称 App01Config
2.settings.py:   INSTALLED_APPS列表注册后面添加   'app01.apps.App01Config'

(四)pycharm终端上启动服务器
C:\Users\admin\AppData\Local\Programs\Python\Python310\python.exe  manage.py runserver
python  manage.py runserver (该python解释器已设置环境变量)
测试  http://127.0.0.1:8000   http://localhost:8000/admin

1-2

#coding:utf-8
"""  app01/views.py 程序  服务器发给前端响应信息"""
from django.shortcuts import render,HttpResponse #return 不是字符串而是对象
# Create your views here.

def index(request):
    html=HttpResponse("<h1>欢迎使用</h1>")
    print(html,type(html))
    return html
# from django.contrib import admin  
from django.urls import path
from app01 import views

urlpatterns = [
    #path('admin/', admin.site.urls),
    path("index/",views.index)
]
""" 测试 127.0.0.1:8000/index  = http://127.0.0.1:8000/index/ 
前端请求urls与服务器响应对应 为什么需要注册app?
"""

1-3

""" app01/views.py程序 """
from django.shortcuts import render,HttpResponse

def user_list(req):
    ren=render(req,"user_list.html")
    print("【user_list】\n",ren)
    print("【user_list】\n",ren.content) #ctrlD
    print("【user_list】\n",ren.content.decode())

    from pathlib import Path
    print("【注意】mysite/settings.py中 有一个变量 BASE_DIR")
    print("【BASE_DIR】\n", Path(__file__),type(Path(__file__)),__file__)
    print("【BASE_DIR】\n", Path(__file__).resolve(),type(Path(__file__).resolve()))
    print("【BASE_DIR】\n", Path(__file__).resolve().parent)
    print("【BASE_DIR】\n",Path(__file__).resolve().parent.parent)
    return ren

def index(request):
    html=HttpResponse("<h1>欢迎使用</h1>")
    print("【user_list】\n",html,type(html))
    print("【user_list】\n",html.content.decode())
    return html
#from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    #path('admin/', admin.site.urls),
    path("index/",views.index),
    path("user/list/",views.user_list)
]
<!-- app01/新建目录 templates /user_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>
</head>
<body>
  <h1>用户列表</h1>
</body>
</html>

<!--
【测试】
 http://127.0.0.1:8000/user/list/   http://127.0.0.1:8000/index
【关联链接的html】
mysite/mysite/settings.py  搜索 TEMPLATES
1.TEMPLATES 'DIRS': [] #发现默认为空 其实默认=TEMPLATES 'DIRS': ["templates"]
2. 如果改为项目 根目录/templates
  #BASE_DIR=mysite项目绝路如改"DIRS":[os.path.join(BASE_DIR,"templates")] 
-->
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
""" app01/views.py user_list会找app01/templates/user_list.html吗"""

2-1 static

 <!--
 【app01/templates/user_list.html】
1.app01包新建 app01/static目录/img cs js plugins等目录
2 百度图片下载 3张成龙相片 放在 appo1/static/img/成龙1.jpg 成龙2.jpeg 成龙3.jpeg
 【Test 】 http://127.0.0.1:8000/  http://127.0.0.1:8000/user/list/
 -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>
</head>
<body>

  <h1>用户列表</h1>
  <h2>成龙1</h2>
  <img src="/static/成龙1.jpg",alt="成龙1"><br>
  <img src="/static/img/成龙1.jpg",alt="成龙1">
  <h2>成龙2</h2>
  <img src="/static/img/成龙2.jpg",alt="成龙2"><br>
  <h2>成龙3</h2>
  {% load static %}
  <img src="{% static 'img/成龙3.jpg' %}" alt="成龙3">

  <h2>网上直接获取</h2>
  <img src="https://img2.baidu.com/it/u=1265458789,2975563618&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500">
  <br><img src="https://img2.baidu.com/" alt="成龙5"> <span>不存在</span><br>

</body>
</html>

2-2

 <!--
 【app01/templates/user_list.html】
一.app01/static/js/jquery.min.js =https://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js
二.下载 bootstrap.min.css/js  https://www.bootcss.com/(可以选择v3 v4 v5)
(一)v3
1.点击Boostrap v3中文文档  BootCDN.cn 查看v3的小版本link_href或 script_src
2.static/plugins/bootstrap3.4.1/bootstrap.min.css
3.static/plugins/bootstrap3.4.1/bootstrap.min.js
(二)v4
可以<下载Bootstrap源码> 多文件中找到 ootstrap.min.css/js文件
1. static/plugins/bootstrap@4.6.2/bootstrap.min.css
2. static/plugins/bootstrap@4.6.2/bootstrap.min.js
 【Test 】 http://127.0.0.1:8000/user/list/
 -->
 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>
  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap-theme.min.css">
</head>
<body>

  <h1>用户列表</h1>
  <input type="text" class="btn btn-primary" value="新建" />
  <input type="text" class="btn btn-primary" value="新建" />

</body>
</html>

2-3

 <!--
 【app01/templates/user_list.html】
 【Test 】 http://127.0.0.1:8000/user/list/
 -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>

  {% load static %} <!--【是否为局部?】-->
  <link rel="stylesheet" href="{% static 'plugins/bootstrap3.4.1/bootstrap.min.css' %}">

</head>
<body>

  <h1>用户列表</h1>
  <input type="text" class="btn btn-primary" value="新建" />
  <input type="text" class="btn btn-primary" value="新建" />

</body>
</html>

2-4

 <!--
 【app01/templates/user_list.html】
 【Test 】 http://127.0.0.1:8000/user/list/
 -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>

  {% load static %}
  <link rel="stylesheet" href="{% static 'plugins/bootstrap@4.6.2/bootstrap.min.css' %}">

</head>
<body>

  <h1>用户列表</h1>
  <input type="text" class="btn btn-primary" value="新建" />
  <input type="text" class="btn btn-primary" value="新建" />

</body>
</html>

2-4

 <!--
 【app01/templates/user_list.html】
 【Test】检查导入css js是否正确 
 http://127.0.0.1:8000/user/list/
 http://127.0.0.1:8000/static/plugins/bootstrap3.4.1/bootstrap.min.css

 http://127.0.0.1:8000/static/js/jquery.min.js (bootstrap.min.js依赖此脚本 需要先导入)
 http://127.0.0.1:8000/static/plugins/bootstrap3.4.1/bootstrap.min.js
 -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>

  {% load static %}
  <link rel="stylesheet" href="{% static 'plugins/bootstrap3.4.1/bootstrap.min.css' %}">
  <script src="{% static 'plugins/js/jquery.min.js' %}"></script>
  <script src="{% static 'plugins/bootstrap3.4.1/bootstrap.min.js' %}"></script>

</head>
<body>

  <h1>用户列表</h1>
  <input type="text" class="btn btn-primary" value="新建" />
  <input type="text" class="btn btn-primary" value="新建" />

</body>
</html>

3-1 jinja

#【app01/templates/user_list.py】
# settings.py已关联url urlpatterns已添加该元素:path("user/list/",views.user_list)
from django.shortcuts import render,HttpResponse

def user_list(request):
    print("【user_list】request对象可以接收客户端发过来的数据",request)
    english_name, chinese_name = "zhangsan", "张三"
    roles= ["管理员", "CEO", "保安"]
    user_info={"name":chinese_name,"salary":3000,"roles":roles}
    data_list=[{"data0": "running", "data1": "basketball"},{"data0": "english", "data1": "math"}]

    return render(request,
                  'user_list.html',
                  {"n1": english_name, "n2": chinese_name, "roles": roles,
                   "user_info": user_info, "data_list": data_list})

def index(request):
    html=HttpResponse("<h1>欢迎使用</h1>")
    return html
<!--
【app01/templates/user_list.html】
【Test】检查导入css js是否正确http://127.0.0.1:8000/user/list/
【summarize】
1 客户端访问url(request对象)->urls.py app01/views.py user_list->返回客户端
2 前端页面(需要响应返回客户端)=前端html+views.py的渲染整合  html文件与views传参交互
3 django_jinja模板 类似于 php网页脚本语言
-->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>userlist(用户列表)</title>
  {% load static %}
  <link rel="stylesheet" href="{% static 'plugins/bootstrap3.4.1/bootstrap.min.css' %}">
  <script src="{% static 'plugins/js/jquery.min.js' %}"></script>
  <script src="{% static 'plugins/bootstrap3.4.1/bootstrap.min.js' %}"></script>

</head>
<body>
      <h1>用户列表--模板语法(templateLanguage) </h1> <hr><!--Non-Breaking Space=&nbsp;-->

      <div>英文姓名:{{n1}} &nbsp;&nbsp;  该字符串长度={{n1|length}}</div>
      <div>中文姓名: {{n2}}  &nbsp;&nbsp; 该字符串长度={{n2|length}}</div><br>

      <div>【列表】{{roles}}&nbsp;遍历列表元素={{roles.0}} &nbsp;{{roles.1}}&nbsp; {{roles.2}}</div>
      <div>for遍历:{%for item in roles%}<span>{{item}}&nbsp;</span>{%endfor%}</div><br>

      <div>【字典】{{user_info}}&nbsp; 列表2元素值={{user_info.name}} {{user_info.salary}}</div>

      <ul> {%for k in user_info.keys %} <li>{{k}}</li> {%endfor%}</ul> <br>
      <ul> {%for v in user_info.values %} <li>{{v}}</li> {%endfor%}</ul> <br>
      <ul> {%for k,v in user_info.items %} <li>{{k}}:{{v}}</li> {%endfor%}</ul> <br>

      <hr> <h3>元素为字典的列表</h3>
      <div>{{data_list}} {{data_list.0}} {{data_list.0.data0}}</div> <br>
      {%for item in data_list%} <p>{{item}}&nbsp;{{item.data0}}&nbsp;{{item.data1}}</p> {%endfor%}

      <hr> <h3>条件判断</h3>
      {% if n1 == 'zhangsan' %} <h4>你好 张三</h4>  {% else %} <h4>你是普通用户</h4> {% endif %}
      {% if n1 == 'lisi' %} <h4>你好 张三</h4>  {% else %} <h4>你是普通用户</h4> {% endif %}

</body>
</html>

3-2

<!--【app01/templates/news.html】-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>新闻中心</title>
</head>
<body>
  <h2>新闻中心</h2>

</body>
</html>
#【app01/templates/user_list.py】测试 127.0.0.1/user/list 127.0.0.1/news
from django.shortcuts import render,HttpResponse

from django.core.handlers.wsgi import WSGIRequest
def news(req:WSGIRequest): #【1】url.py 添加  path("news",views.news)
    print("【news】",req,type(req),req.path,req.method,req.body)
    print("【news】req.headers=\n",req.headers)
    print("【news】\n")
    for i,(k,v) in enumerate(req.headers.items()):
        print(f"[{i+1}]",k,v)
    return render(req, "news.html")

def user_list(request):
    print("【user_list】request对象可以接收客户端发过来的数据",request)
    english_name, chinese_name = "zhangsan", "张三"
    roles= ["管理员", "CEO", "保安"]
    user_info={"name":chinese_name,"salary":3000,"roles":roles}
    data_list=[{"data0": "running", "data1": "basketball"},{"data0": "english", "data1": "math"}]

    return render(request=request,
                  template_name='user_list.html',
                  context={"n1": english_name, "n2": chinese_name, "roles": roles,
                   "user_info": user_info, "data_list": data_list}
    )

def index(request):
    html=HttpResponse("<h1>欢迎使用</h1>")
    return html

3-4

import time

from django.shortcuts import render,HttpResponse
import requests

def news(req):
    #url='http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2023/08/news' #现在已经不能访问
    #requests.get(url, headers=headers).json(); #上述请求 可以获取响应的 “元素为字典的列表”字符串

    url=r'http://www.chinaunicom.com.cn/43/menu01/1/column05?pageNo=0&pageSize=50&year=2023&month=12'

    h='Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36'
    headers={"User-Agent":h,"Host":"www.chinaunicom.com.cn","Upgrade-Insecure-Requests":"1"}
    session=requests.Session()
    res=session.get(url, headers=headers)
    time.sleep(1)
    res = session.get(url, headers=headers)
    #print(res.url,res.headers)
    #print(res.request.headers)

    res.encoding="utf8"
    ## "div.template-list-text  tbody  tr  td:nth-child(odd)"  #odd even
    ## "div.template-list-text  tbody  td:nth-child(odd)"
    print(res.text)

    datas=re.findall(r'<td width="1000".*?>(.*?)</td>.*?<td align="right".*?>(.*?)</td>',res.text,re.S)
    print("【news】",datas)
    data_list=[]
    for d in datas:
        data_list.append({"news_title":d[0],"post_time":d[1]})

    return render(req,"news.html",{"news_list":data_list})
<!--【app01/templates/news.html】-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>新闻中心</title>
</head>
<body>
  <h2>新闻中心</h2>

  <ul>

    {% for item in news_list %}
    <li>{{item.news_title}} &nbsp;&nbsp; {{item.post_time}}</li>
    {%endfor%}

  </ul>

</body>
</html>

4-1

# path("user/add/",views.user_add) 
# 【TEST】 http://127.0.0.1:8000/user/add/?a=11&b=21,22,23
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
def user_add(request):
    tests=[request.method,request,request.GET,request.POST]
    for i,t in enumerate(tests):
        print(f"【{i}】",t)
    #return HttpResponse("添加用户") #HttpResponse(串) render(req,"html",{}) redirct()
    return redirect("https://www.baidu.com") #重定向网站已发给客户端 由客户端访问重定向的网页
    #return HttpResponseRedirect("https://www.baidu.com") # 两者一样 redirect应该是简称

4-2

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户登录界面</title>  <!--user_login.html -->
</head>
<body>

  <h1>用户登录</h1>            <!--跨站请求伪造(英语:Cross-site request forgery)-->
  <form method="post" action="">
    {% csrf_token %} <!--需要安全验证 否则GE请求或者报错-->
    <input type="text" name="user" placeholder="用户名">
    <input type="password" name="pwd" placeholder="密码">
    <input type="submit" value="提交" /><br><br>{{error_msg}}

    <br><br><span>{{error_msg}}</span>
  </form>

</body>
</html>
def user_login(req): ## views.py
    print("\n【获取客户端请求数据】",req.GET)
    print("【获取客户端请求数据】",req.POST)
    if req.method=="GET":
        return render(req,"user_login.html")
    else: ##可以去掉else:
        username,pwd=req.POST.get("user"),req.POST.get("pwd")
        print("【1】req= ",req," req.POST= ",req.POST)
        print("【2】",req.POST.get("csrfmiddlewaretoken"))

        if username=="root" and pwd=="123":return HttpResponse("登录成功")
        else:
            #return HttpResponse("用户登录失败...")
            error="用户名称或者用户密码输入错误,请重新输入..."
            return render(req,"user_login.html",{"error_msg":error}) #错误信息传递

# path("user/login/",views.user_login),
#【TEST】 http://127.0.0.1:8000/user/login?a=11&b=21,22,23

二.django-mysql

1. django_ORM模型创建第1表

mysql 已安装完毕 import pymysql
一. django_ORM不能创库 如下面创建数据库 mydjango
alter user "root"@"localhost" identified by "mysqladmin";
exit; mysql -uroot -pmysqladmin
alter user "root"@"localhost" identified by "123456"; -- 修改成简单M码
exit; mysql -uroot  -p123456 -P3306
exit; mysql -h localhost -uroot -p123456
exit;
mysql -h 127.0.0.1 -uroot -p123456

show databases ; drop database if exists mydjango;
create database if not exists mydjango default charset utf8 collate utf8_general_ci;
#MySQL数据库中的一种字符集排序规则,utf8表示字符集 general匹配的字符比较类型
#ci大小写不敏感 character ignore

二. django_ORM
(一)注册mysql
# mysite(方案)/mysite(全局设置目录)/settings.py

INSTALLED_APPS =[ 'app01.apps.App01Config']
# 【app01注册方法】app01包先前已经注册 app01=包 apps=py文件 App0cConfig是apps.py文件中的类

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

DATABASES={
    'default':{'ENGINE':'django.db.backends.mysql','NAME':'mydjango','USER':'root',
                'PASSWORD': '123456','HOST': '127.0.0.1','PORT': '3306'}
}

(二)app01/models.py (本身有文件)

from django.db import models
# Create your models here.

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField()

(三) 生成数据表  pycharm终端 PS J:\common\pyproject\py2024_2\mysite> cmd命令
1.两条命令
python manage.py makemigrations  #自动生成一个包 app01/migrations 注意不要删除?不可恢复吗?
python manage.py migrate #在数据库中自动生成很多表

2.命令执行情况 mysql查看
use mydjango ; show tables; #默认10表 新增1表=app01_userinfo(如果没有该表 再重新执行上述两条命令)
desc app01_userinfo; show create tables 表名; -- 创建表结构如下:

 CREATE TABLE `app01_userinfo` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `password` varchar(64) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci

2.数据库软件/登录及库=已注册 再建两表 models.py

from django.db import models
# Create your models here.

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField()

class Department(models.Model):
    title=models.CharField(max_length=16)

class Role(models.Model): #caption说明文字
    caption=models.CharField(max_length=16)

# python manage.py makemigrations  #显示创建上述两个模型 看migrations目录变化
# python manage.py migrate #写库 show tables; desc 表名; show create table 表名

3.在原表增加或修改字段 models.py两命令

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=18) #修改字段 默认为18
    date=models.DateField(null=True,blank=True)
    size=models.IntegerField(default=2) #默认为2 该默认值不会写入数据库的设置?
"""
python manage.py makemigrations # migrations目录
python manage.py migrate  #show tables desc表名; show create table表名
"""

三.创建库的表

1-1 添加数据

"""
【app01/views.py】
1.[urls.py]  path("orm/",views.orm)
2.python  manage.py runserver # http://127.0.0.1:8000/orm/
"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 数据库模型的引入

def orm(request):
    titles=["销售部","IT部","运营部"]
    print("【1】",hasattr(Department, "objects"),"use mydjango; show tables; select * from app01_department;")
    for t in titles:
        Department.objects.create(title=t)
    print("【2】","多次运行后,表数据不断增加","[truncate table app01_department;]只删除表的所有记录(数据)但表结构不删除")
    return HttpResponse("<h1>数据库操作成功</h1>")

1-2

"""【app01/views.py】[urls.py]  path("orm/",views.orm)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 数据库模型的引入

def orm(request):
    UserInfo.objects.create(name='zs', password='123', age=19)  # select * from app01_userinfo;
    UserInfo.objects.create(name='li', password='123')  # age已设置默认值=18
    UserInfo.objects.create(name='ww', password='123456')
    print("【0】",'insert into app01_userinfo(name,password,age)values("zs","123",19);') #双引号 单引号均可用
    print("【0】","insert into app01_userinfo(name,password,age)values('li','123',18),('ww','123456',18);")

    querySet_asList = UserInfo.objects.all()
    print("【1】", querySet_asList)
    print("【2】","select * from app01_userinfo;","truncate table app01_userinfo;")

    html='<h1>数据库操作成功</h1> <ul>'
    for i,user in enumerate( querySet_asList):
        print(f"[{i+1}]",user.id,user.name,user.password,user.age,user.date,user.size)
    # return HttpResponse(content=html,content_type="text/plain",status=200,charset="gbk")
    return HttpResponse(content=html)

2查询

"""【app01/views.py】[urls.py]  path("orm/",views.orm)"""
from app01.models import Department,UserInfo,Role # 数据库模型的引入

def orm(request):
    querySet_all = UserInfo.objects.all()
    print("\n【0】", querySet_all,end="\n"*2)
    for i, obj in enumerate(querySet_all):
        print(f"[{i + 1}]",obj.id, obj.name, obj.password, obj.age)

    user = UserInfo.objects.filter(id=1)[0]
    print("\n【1】", user, "=",user.name, user.age)
    UserInfo.objects.filter(id=3).delete()
    print("【2】id=3 不存在了:",UserInfo.objects.filter(id=3))
    return HttpResponse(content="<h1>数据库查询: id=3 被删除了 </h1>")

3清空

"""【app01/views.py】[urls.py]  path("orm/",views.orm)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 数据库模型的引入

def orm(request):
    UserInfo.objects.all().update(password=999) #没有数据将全报错
    print("\n【1】批量修改M码")
    for i,u in enumerate(UserInfo.objects.all()):
        print(f"[{i+1}]",u.id,u.name,u.password)
    UserInfo.objects.filter(id=1).update(password="111111")
    print("\n【2】")
    print(UserInfo.objects.filter(id=1))
    print(UserInfo.objects.filter(id=1)[0].password)

    UserInfo.objects.all().delete()
    print("\n【2】清空数据  ", UserInfo.objects.all())
    print("""
         truncate table app01_userinfo;  -- id也从1开始计算
         insert into app01_userinfo(name,password,age)values('zs','123',19),
         ('li','123',18),('ww','123',18);
    """)
    return HttpResponse(content="<h1>数据库修改 删除 </h1>")

4添加默认值

"""【app01/views.py】[urls.py]  path("orm/",views.orm)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 数据库模型的引入

def orm(request):
    print("【0】\nshow tables; select * from app01_department; ")
    print("desc app01_department; show create table app01_department;")
    print("class Department(models.Model):title=models.CharField(max_length=16,default='人事部')\n")
    Department.objects.create()
    for i, d in enumerate(Department.objects.all()):
        print(f"[{i + 1}]", d, d.title)

    return HttpResponse(content="<h1>添默认值 http://127.0.0.1:8000/orm/ 多次运行重复 要求不重复的</h1>")

四.数据库展示

1-1 显示

"""【0】app01/views.py 【1】urls.py  path("info/list/",views.info_list)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 【2】app01/models.py

def info_list(r):
    print("\n【0】表有数据")
    print('''
         truncate table app01_userinfo; -- id也从1开始计算 UserInfo.objects.all().delete() #类似列表所有元素删除
         desc app01_userinfo; show create table app01_userinfo;
         
           CREATE TABLE if not exists  `app01_userinfo` (
              `id` bigint(20) NOT NULL AUTO_INCREMENT,
              `name` varchar(32) NOT NULL,
              `password` varchar(64) NOT NULL,
              `age` int(11) NOT NULL,
              `date` date DEFAULT NULL,
              `size` int(11) NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ; 
        
         insert into app01_userinfo(name,password,age)values('zs','123',19),('li','123',18),('ww','123',18);
         select * from app01_userinfo where age=19;
    ''')

    print("\n【1】添加3条数据")
    UserInfo.objects.create(name='user1',password='123',age=19)
    UserInfo.objects.create(name='user2',password='123') #age已设置默认值=18
    UserInfo.objects.create(name='user3', password='123')

    for i, u in enumerate(UserInfo.objects.all()):
        print(f"[{i+1}]",u.id,u.name,u.password,u.age)
    print()

    return render(request=r, template_name= "info_list.html",   #【3】app01/templates/info_list.html
                  context={"data_list": UserInfo.objects.all()}
    )
# 【2】app01/models.py 没有修改 Create your models here.
from django.db import models

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=18) #修改字段 默认为18
    date=models.DateField(null=True,blank=True)
    size=models.IntegerField(default=2) #默认为2 该默认值不会写入数据库的设置?
"""
python manage.py makemigrations # migrations目录
python manage.py migrate  #show tables desc表名; show create table表名
"""

class Department(models.Model):
    title=models.CharField(max_length=16,default="人事部")

class Role(models.Model): #caption说明文字
    caption=models.CharField(max_length=16)
<!-- 【3】app01/templates/info_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户列表</title>
</head>
<body>
    <h1>INFO用户列表</h1>
    <table border="1">
      <thead><tr><th>ID</th><th>姓名</th><th>密码</th><th>年龄</th></tr></thead>
      <tbody>
           <tr><td>0</td><td>数据库不存在用户</td> <td>123</td><td>19</td></tr>
      </tbody>
    </table>
</body>
</html>

1-2

"""【0】app01/views.py 【1】urls.py  path("info/list/",views.info_list)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 【2】app01/models.py

def info_list(r):
    print("\n【0】表有数据")
    for i, u in enumerate(UserInfo.objects.all()):
        print(f"[{i+1}]",u.id,u.name,u.password,u.age)
    print()
    return render(r,"info_list.html", {"data_list": UserInfo.objects.all()}) 
<!-- 【3】app01/templates/info_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户列表</title>
</head>
<body>

<h1> views.py 传递过来的数据</h1>  {{data_list}}
<h1>获取第一个值数据</h1>
{{data_list.0}}<br> {{data_list.0.id}}<br> {{data_list.0.name}}<br> {{data_list.0.password}}<br>

<h1>INFO用户列表</h1>
<table border="1">
    <thead>
        <tr><th>ID</th><th>姓名</th><th>密码</th><th>年龄</th></tr>
    </thead>
    <tbody>
        {% for d in data_list %}
           <tr><th>{{d.id}}</th><th>{{d.name}}</th><th>{{d.password}}</th><th>{{d.age}}</th></tr>
        {% endfor %}
     </tbody>

</table>

</body>
</html>

2-1 添加

"""【0】app01/views.py 【1】urls.py  path("info/add/",views.info_add)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 【2】app01/models.py

def info_add(req):
    print("\n【0】")
    print('''
        truncate table app01_userinfo; -- UserInfo.objects.all().delete() 
        select * from app01_userinfo;
        desc app01_userinfo; show create table app01_userinfo; \n
    ''')

    print("\n【1】请求参数\n", req, req.POST, req.GET)

    if req.method=="GET":
        return render(req, "info_add.html")

    u,p,a= req.POST.get("user"),req.POST.get("pwd"),req.POST.get("age")
    UserInfo.objects.create(name=u,password=p,age=a)
    return HttpResponse("测试 http://127.0.0.1:8000/info/add/?q1=11,12,13&q2=ab&q3=3 添加成功")
<!-- 【3】app01/templates/info_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户列表</title>
</head>
<body>

<h1> app01/templates/info_list.html </h1>
<a href="http://127.0.0.1:8000/info/add"> href="http://127.0.0.1:8000/info/add"绝对链接添加用户</a><br><br>
<a href="/info/add"> 【常用】href="/info/add" 相对链接添加用户</a><br><br>

<h1>INFO用户列表</h1>

<table border="1">
    <thead>
        <tr><th>ID</th><th>姓名</th><th>密码</th><th>年龄</th></tr>
    </thead>
    <tbody>
        {% for d in data_list %}
           <tr><th>{{d.id}}</th><th>{{d.name}}</th><th>{{d.password}}</th><th>{{d.age}}</th></tr>
        {% endfor %}
     </tbody>

</table>

</body>
</html>
 <!--app01/templates/info_add.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>添加用户</title>
</head>
<body>

<h1>添加用户</h1>
<form method="post" action="/info/add/"> <!--向当前网页POST action可省-->
  {% csrf_token %} <!--跨站请求伪造Cross-site request forgery-->
  <input type="text" name="user" placeholder="用户名">
  <input type="password" name="pwd" placeholder="密码">
  <input type="text" name="age" placeholder="年龄">
  <input type="submit" value="提交">
</form>

</body>
</html>

2-2

def info_add(req):
    print("\n【1】请求参数\n", req, req.POST, req.GET)

    if req.method=="GET":
        return render(req, "info_add.html")

    u,p,a= req.POST.get("user"),req.POST.get("pwd"),req.POST.get("age")
    UserInfo.objects.create(name=u,password=p,age=a)
    print("【2】测试 http://127.0.0.1:8000/info/add/?q1=11,12,13&q2=ab&q3=3 添加成功")

    #return redirect("http://127.0.0.1:8000/info/list")
    return redirect("/info/list") #是否在链接后面加"/" 看urls.py 【常用】相对链接

3-1 删除

<!-- app01/templates/info_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用户列表</title>
</head>
<body>

<h3>app01/templates/info_list.html</h3>
<h3>python manage.py runserver</h3>
<a href="/info/list"> 测试 http://127.0.0.1:8000/info/list </a>
<h1>INFO用户列表</h1>

<table border="1">
    <thead>
        <tr>
          <th>ID</th><th>姓名</th><th>密码</th><th>年龄</th>
          <th>操作</th>  <!-- 增加一列字段名为操作 -->
        </tr>
    </thead>
    <tbody>
        {% for d in data_list %}
           <tr>
               <td>{{d.id}}</td>
               <td>{{d.name}}</td>
               <td>{{d.password}}</td>
               <td>{{d.age}}</td>
               <td> <a href="#">删除</a> </td>  <!-- 增加一项数据 删除 -->
           </tr>
        {% endfor %}
     </tbody>

</table>

</body>
</html>

3-2

"""【0】app01/views.py 【1】urls.py  path("info/delete/",views.info_delete)"""
import time,re,requests
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from app01.models import Department,UserInfo,Role # 【2】app01/models.py

from django.core.handlers.wsgi import WSGIRequest #代码有提示的功能
from django.db.models.base import ModelBase ##代码有提示的功能 但方法objects仍有警告提示

def info_delete(r:WSGIRequest,UserInfo:ModelBase=UserInfo):
    nid = r.GET.get("nid")
    print("【0】UserInfo.objects.filter(id=nid) ",UserInfo.objects.filter(id=nid))
    UserInfo.objects.filter(id=nid).delete()  # 删除是列表
    print("【1】UserInfo.objects.filter(id=nid) ", UserInfo.objects.filter(id=nid))
    print("【2】测试(链接没有此网页 危险操作高危漏洞添加多个数据 再进行操作测试)")
    print("http://127.0.0.1:8000/info/delete/?nid=7    2   3")
    return redirect("/info/list")  # return HttpResponse("删除成功")

3-3 删除项目重练

<h2> app01/templates/info_list.html </h2>
<h2>【测试删除】 http://127.0.0.1:8000/info/list/</h2>
  
<h1>INFO用户列表</h1>
<table border="1">
    <thead>
        <tr>
          <th>ID</th><th>姓名</th><th>密码</th><th>年龄</th>
          <th>操作</th>  <!-- 增加一列字段名为操作 -->
        </tr>
    </thead>
    <tbody>
        {% for d in data_list %}
           <tr>
               <td>{{d.id}}</td>
               <td>{{d.name}}</td>
               <td>{{d.password}}</td>
               <td>{{d.age}}</td>
             
                <!-- 【测试删除】 http://127.0.0.1:8000/info/list/ -->
               <td> <a href="/info/delete/?nid={{d.id}}">删除</a> </td>

           </tr>
        {% endfor %}
     </tbody>
</table>
def info_delete(r:WSGIRequest,UserInfo:ModelBase=UserInfo): #【app01/views.py】
    nid = r.GET.get("nid")
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/info/list")

https://www.xamrdz.com/backend/3fx1945669.html

相关文章: