前言
本文是记录DjangoWeb 应用框架+MySQL数据库第三次培训的笔记,包含
Django小白入门到实战教程(2021)_哔哩哔哩_bilibili
P6-P11的学习笔记,以及Django的ORM学习笔记
感谢梅姐的教学!
1.DJango路由
路由简单的来说就是根据用户请求的 URL 链接来判断对应的处理程序,并返回处理结果,也就是 URL 与 Django 的视图建立映射关系。
Django 路由在 urls.py 配置,urls.py 中的每一条配置对应相应的处理方法。
1.1配置urls路由
首先,在djangoProject文件夹下新建一个app,命名为student,启动终端,在C:\Users\11252\Desktop\djangoProject路径下输入如下代码即可。
python manage.py startapp student
如上图,app创建完成。
下一步,修改settings.py文件。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'student', #新增student
]
修改djangoProject文件夹下的urls.py文件。
from django.contrib import admin
from django.urls import path, include #新增include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('student.urls')), #新增student路径
]
修改student文件下的urls.py文件,复制上方代码,再修改即可。
from django.urls import path
urlpatterns = [
]
2.展示HTML页面
启动Django服务时,将展示出home页面。
编写student文件下的urls.py文件,准备展示home页面
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home")
]
在student文件下新建templates文件夹,在templates文件夹下创建home.html文件,并编写Hello World!
<h1>Hello World!</h1>
编写views.py,新增home方法
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'home.html', {})
启动django服务
python manage.py runserver 127.0.0.1:8000
效果如下:
3.创建公共HTML模板
使用bootstrap框架美化页面,要用到Bootstrap4的入门模板,链接如下:
简介 · Bootstrap v4 中文文档 v4.6 | Bootstrap 中文网 (bootcss.com)
复制入门模板代码
<!doctype html>
<html lang="zh-CN">
<head>
<!-- 必须的 meta 标签 -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 的 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-p1KAotb3W9ndluCsqePPYnjRm3c6abdnIjo0tQwYUv83VsbsYd43RuofnFAaDo0E" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- JavaScript 文件是可选的。从以下两种建议中选择一个即可! -->
<!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-E5Sj1saJVFNzWWK3YIJB4LEDEEVEGaOdfmCprPDkfWUo+xkb6Ep52Q1TMEtgcFwi" crossorigin="anonymous"></script>
<!-- 选项 2:Popper 和 Bootstrap 的 JS 插件各自独立 -->
<!--
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-IjeXbuVdL81ilB5LykkImU8JN0WPja/i9uZAt2qjo2TnYk9NJ2MPfN3vzMH0R8n3" crossorigin="anonymous"></script>
-->
</body>
</html>
在templates文件夹下创建base.html文件,并将上方代码粘贴到此文件中,修改home.html文件,代码如下:
{% extends 'base.html' %}
{% block content %}
<h1>Hello World!</h1>
<p>测试是否可以看到我</p>
{% endblock %}
在base.html文件中调用home.html并写入导航link
<!doctype html>
<html lang="zh-CN">
<head>
<!-- 必须的 meta 标签 -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 的 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-p1KAotb3W9ndluCsqePPYnjRm3c6abdnIjo0tQwYUv83VsbsYd43RuofnFAaDo0E" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
#在这里!!!
<body>
link1 || link2 || link3
{% block content %}
{% endblock %}
#在这里!!!
<!-- JavaScript 文件是可选的。从以下两种建议中选择一个即可! -->
<!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-E5Sj1saJVFNzWWK3YIJB4LEDEEVEGaOdfmCprPDkfWUo+xkb6Ep52Q1TMEtgcFwi" crossorigin="anonymous"></script>
<!-- 选项 2:Popper 和 Bootstrap 的 JS 插件各自独立 -->
<!--
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-IjeXbuVdL81ilB5LykkImU8JN0WPja/i9uZAt2qjo2TnYk9NJ2MPfN3vzMH0R8n3" crossorigin="anonymous"></script>
-->
</body>
</html>
效果如下:
4.展示导航信息
导航条代码来源Navbar · Bootstrap v4 中文文档 v4.6 | Bootstrap 中文网 (bootcss.com)
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
效果如下:遇到了未知bug,效果和预期不同!!!(bug已修复,link标签加载css资源失败是因为哈希校验不通过,把integrity和crossorigin属性删除即可)
5.接口请求和解析
接口地址:https://api.github.com/users?since=0
准备工作:在终端输入pip install requests,安装requests插件。
在views.py文件里做以下修改,导入接口,最后return将获取的数据放入home页面
from django.shortcuts import render
# Create your views here.
def home(request):
import requests
import json
api_request = requests.get("https://api.github.com/users?since=0")
api = json.loads(api_request.content)
return render(request, 'home.html', {"api":api})
在home.html文件里做以下修改,将获取的数据放入home页面
{% extends 'base.html' %}
{% block content %}
<h1>Hello World!</h1>
<p>{{ api }}</p>
{% endblock %}
效果如下,可以看到导航条已经恢复了:
6.DJango ORM实现增、删、改、查
6.1准备工作
先建表,并重新展示页面,这里以学生管理表为例
在models.py文件中写入如下代码:
from django.db import models
# Create your models here.
class Students(models.Model):
Name=models.CharField(max_length=12)
Email=models.IntegerField(max_length=20)
Age=models.IntegerField(max_length=12)
djangoProject路径下的urls文件做出修改,新增student_list页面路径
from django.contrib import admin
from django.urls import path, include
from student import views
urlpatterns = [
path('admin/', admin.site.urls),
path('three', include('student.urls')),
path('student_list', views.student_list),
]
在views.py中新增代码
def student_list(request):
student_queryset = models.Students.objects.all()
# person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
# print(person1, type(person1))
return render(request, "student.html", {"student_queryset": student_queryset})
编写student.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生管理</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<td>id</td>
<td>姓名</td>
<td>邮箱</td>
<td>年龄</td>
</tr>
</thead>
<tbody>
{% for student in student_queryset %}
<tr>
<td>{{ student.id }}</td>
<td>{{ student.Name }}</td>
<td>{{ student.Email }}</td>
<td>{{ student.Age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
迁移表格,执行迁移
python manage.py makemigrations
python manage.py migrate
在student_students数据库中手动写入数据
def student_list(request):
student_queryset = models.Students.objects.all()
person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
print(person1, type(person1))
return render(request, "student.html", {"student_queryset": student_queryset})
访问新页面,如图,准备工作完成
6.2 增的实现
UserInfo.objects.create(username='root',passwd='123456')
在views.py下的student_list方法中增加orm的增操作,如下
def student_list(request):
student_queryset = models.Students.objects.all()
person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
print(person1, type(person1))
return render(request, "student.html", {"student_queryset": student_queryset})
效果如下:
6.3 删的实现
UserInfo.objects.filter(id=19).delete()
在views.py下的student_list方法中增加orm的删除操作,删除id=1的数据,如下
def student_list(request):
student_queryset = models.Students.objects.all()
# person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
# print(person1, type(person1))
person2 = models.Students.objects.filter(id=1).delete()
print(person2, type(person2))
return render(request, "student.html", {"student_queryset": student_queryset})
效果如下:
6.3 查和改的实现
filter用来查询符合条件的
User.objects.filter(id__gt=10).update(Name='white')
exclude() 方法用于查询不符合条件的数据
User.objects.objects.exclude(Name=’D’) .update(Name='white')
在views.py下的student_list方法中增加orm的filter查询操作,更改id=2数据的Name,如下
def student_list(request):
student_queryset = models.Students.objects.all()
# person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
# print(person1, type(person1))
# person2 = models.Students.objects.filter(id=1).delete()
# print(person2, type(person2))
person3 = models.Students.objects.filter(id=2).update(Name='DEV')
print(person3, type(person3))
return render(request, "student.html", {"student_queryset": student_queryset})
效果如下:
在views.py下的student_list方法中增加orm的exclude查询操作,更改所有不符合id=2数据的Name,如下
def student_list(request):
student_queryset = models.Students.objects.all()
# person1 = models.Students.objects.create(Name="如来", Email=200000, Age=8888)
# print(person1, type(person1))
# person2 = models.Students.objects.filter(id=1).delete()
# print(person2, type(person2))
# person3 = models.Students.objects.filter(id=2).update(Name='DEV')
# print(person3, type(person3))
person4 = models.Students.objects.exclude(id=2).update(Name='DEV')
print(person4, type(person4))
return render(request, "student.html", {"student_queryset": student_queryset})
效果如下:
OK,今天的笔记就写到这里啦!