阅读:68
第一步,
创建项目 模块开发
一个命令行工具,用来和Django项目进行交互,如前面创建项目就用到了该文件。
"""
Django settings for TestDjango2 project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
#安全密钥
SECRET_KEY = 'hdixe=$#4p8gwyt-a$mj$+rzl@0-$o!0=jxy^^f5h_o&_-l2^7'
# SECURITY WARNING: don't run with debug turned on in production!
#是否开启Debug
DEBUG = True
# 允许访问的主机ip,可以用通配符*
ALLOWED_HOSTS = []
# Application definition
# 用来注册App 前6个是django自带的应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'student.apps.StudentConfig',
]
# 中间件 ,需要加载的中间件。比如在请求前和响应后根据规则去执行某些代码的方法
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 指定URL列表文件 父级URL配置
ROOT_URLCONF = 'TestDjango2.urls'
# 加载网页模板路径
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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',
],
},
},
]
# WSGI的配置文件路径
WSGI_APPLICATION = 'TestDjango2.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
# 数据库配置 默认的数据库为sqlite
DATABASES = {
'default': {
#将之改为mysql数据库,然后重新运行此项目,报错MySQLdb信息的话,去__init__.py修改配置信息,再重新运行即可。
'ENGINE': 'django.db.backends.mysql',
# 'NAME': BASE_DIR / 'db.sqlite3',
'NAME':'test',
'USER':'root',
'PASSWORD':'123456',
'HOST':'127.0.0.1',
'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
# 相关密码验证
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
# 语言设置 默认英语, 中文是zh-hans
LANGUAGE_CODE = 'en-us'
# 时区设置,中国的是:Asia/Shanghai
TIME_ZONE = 'UTC'
# i18n字符集是否支持
USE_I18N = True
USE_L10N = True
# 是否使用timezone
# 保证存储到数据库中的是 UTC 时间;
# 在函数之间传递时间参数时,确保时间已经转换成 UTC 时间
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
# 静态文件路径
STATIC_URL = '/static/'
admin:对应应用后台管理配置文件
apps:对应应用的配置文件
models:数据模块,用于设计数据库等
tests:编写测试脚本
views:视图层,直接和浏览器进行交互
每次新建一个App我们需要将其在settings.py文件中的INSTALLED_APPS里进行注册,这样程序才能够找到这个服务
# 本文件在项目启动时会重新加载编译一次,在本项目导入pymsql之后,在这个文件里导入pymysql
import pymysql
# 将pymysql作为MySQLdb
pymysql.install_as_MySQLdb()
在下面Terminal控制台 输入命令 python manage.py inspectdb > student/models.py 将数据库表生成实体类,上次的代码放在student/models.py
把数据库里面的表自动生成实体类
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
# 在下面Terminal控制台 输入命令 python manage.py inspectdb > student/models.py 将数据库表生成实体类,上次的代码放在student/models.py
class Student(models.Model):
sid = models.AutoField(primary_key=True)
sname = models.CharField(max_length=255, blank=True, null=True)
ssex = models.CharField(max_length=255, blank=True, null=True)
sage = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'student'
视图层
打开TestDjango目录下的view.py,
from django.db.models import Q
from django.shortcuts import render
from student.models import Student
from django.shortcuts import redirect
# Create your views here.
def index(request):
# return HttpResponse("Hello World")
#测试 返回页面,并携带数据
# name ="老大"
#模拟对象集合
# students=[
# {"sid":6,"sname":"关晓彤","ssex":"女","sage":23},
# {"sid":3,"sname":"张三","ssex":"女","sage":23},
# {"sid":4,"sname":"李四","ssex":"女","sage":23}
# ]
#查询数据库
students=Student.objects.all()
count=students.__len__()
# 返回网页地址并携带学生数据
return render(request,"index.html",context={"students":students,"count":count})
# 根据首页输入框模糊查询
def findStudent(request):
# 获取搜索框的值
str = request.POST.get("str")
# 模糊查询(根据姓名或者性别或者年级查询)
#如果是不区分大小写, icontains不区分大小写 contains 区分大小写
students = Student.objects.filter(Q(sname__icontains=str)|Q(ssex__icontains=str))
# 获取数据的总条数
count = students.__len__()
return render(request, "index.html", context={"students": students, "count": count})
# 添加学生
def addStudent(request):
if request.method=='POST':
#如果是提交的方式是post 添加数据
#就是在添加页面add.html 点击提交数据,添加到数据库
sname=request.POST.get("sname")
ssex = request.POST.get("ssex")
sage = request.POST.get("sage")
#Django提供的方法,只有删除要想查询是否有数据才可以删,就是先Student.objects.get 方法然后 .delete方法
Student.objects.create(sname=sname,ssex=ssex,sage=sage)
# 重定向 index.html
return redirect("index.html")
# return render(request,"index.html")#Z转发
else:
#t 转发 跳转页面add.html
#如果提交的方式是get 就是在首页点击添加
return render(request,"add.html")
# 修改学生
def updateStudent(request):
# 根据表单提交的方式判断是在index.html点击修改操作还是在update.html修改之后提交数据库
if request.method == "GET":
#如果提交方式是get 点击某对象的操作里的修改
# 获取 点击修改 传过来的id
sid = request.GET['update_sid']
# 根据 sid 查询单个对象的所有信息
student = Student.objects.get(sid=sid)
# 跳转到修改页面,并携带修改对象的信息
return render(request, "update.html", context={"student": student})
else:
# 如果提交方式是POST 表单提交,进行信息修改
# 获取需要修改的学生对象的信息
update_sid=request.POST.get("sid")
update_student = Student.objects.get(sid=update_sid)
update_sname=request.POST.get("sname")
update_ssex=request.POST.get("ssex")
update_sage=request.POST.get("sage")
# 修改对象的信息
update_student.sname=update_sname
update_student.ssex=update_ssex
update_student.sage=update_sage
# 保存对象到数据库
update_student.save()
# 重定向到首页,显示学生信息
return redirect("index.html")
# 删除学生
def deleteStudent(request):
# 获取要删除的sid
delete_sid=request.GET['delete_sid']
# 先查找单个对象,然后进行删除
Student.objects.get(sid=delete_sid).delete()
# 删除之后,重定向到首页
return redirect("index.html")
声明请求url的映射
urls.py
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<script>
{# 确认删除框#}
function del(stu_sid) {
var i = confirm("确认删除吗?")
if (i == true) {
location.href = "deleteStudent?delete_sid=" + stu_sid;
}
}
</script>
<body>
<h1>学生信息管理系统<font size="2">©CSDN-ID:yaoyulan21</font></h1>
{#你好!{{ name }}#}
<br/>
<form action="findStudent" method="post">
{#表单提交都要添加防御机制#}
{% csrf_token %}
<input type="text" name="str" placeholder="此处填写姓名或性别"><input type="submit" value="搜索">   
<a href="add.html">添加</a>
</form>
<br/>
<table border="1">
<thead>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</thead>
<tbody>
{#将views.py返回的学生集合数据context中的键students通过for循环遍历#}
{% for student in students %}
<tr>
<td>{{ student.sid }}</td>
<td>{{ student.sname }}</td>
{% if student.ssex == '1'%}
<td>男</td>
{% else %}
<td>女</td>
{% endif %}
<td>{{ student.sage }}</td>
<td>
<a href="updateStudent?update_sid={{ student.sid }}">修改</a>|
<a href="javascript:del({{ student.sid }})">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div style="margin-right:15px">共{{ count }}条记录</div>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改页面</title>
</head>
<body>
<div align="center">
<h3>修改学生</h3>
<form action="updateStudent" method="post">
{#在 templete 中, 为每个 POST form 增加一个 {% csrf_token %} tag,这是Django的防御机制#}
{% csrf_token %}
<input type="hidden" value="{{ student.sid }}" name="sid">
姓名:<input type="text" value="{{ student.sname }}" name="sname"><br>
性别:
{# <input type="text" value="{{ student.ssex }}" name="ssex">#}
{% if student.ssex == '1' %}
男<input type="radio" name="ssex" checked="checked" value="1"/>
女<input type="radio" name="ssex" value="0"/>
{% else%}
男<input type="radio" name="ssex" value="1"/>
女<input type="radio" name="ssex" checked="checked" value="0"/>
{% endif %}
<br>
年龄:<input type="text" value="{{ student.sage }}" name="sage"><br>
<input type="submit" value="修改">
</form>
</div>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加页面</title>
</head>
<body>
<h1>添加学生</h1>
{#<form action="add.html?sid={{ stid }}" method="post">#}
<form action="add.html" method="post">
{#在 templete 中, 为每个 POST form 增加一个 {% csrf_token %} tag,这是Django的防御机制#}
{% csrf_token %}
姓名:<input type="text" name="sname"/><br/>
性别:男<input type="radio" name="ssex" value="1" checked="checked"/>女<input type="radio" name="ssex" value="0"/><br/>
{# <input type="text" name="ssex"/>#}
{# 男<input type="radio" name="gender" value="1"/>女<input type="radio" name="gender" value="0"/>#}
年龄:<input type="number" name="sage"/><br/>
<input type="submit" value=" 添加 "/><br/>
</form>
</body>
</html>
数据库
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1
Source Server Type : MySQL
Source Server Version : 50559
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 50559
File Encoding : 65001
Date: 28/02/2021 14:48:42
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`sname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`ssex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sage` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`sid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
练手demo,不对的地方请大家多多指正,谢谢
链接:https://pan.baidu.com/s/1GmytR6qV_EQPHexPRZg95A
提取码:7jzy
复制这段内容后打开百度网盘手机App,操作更方便哦