利用Django实现MySQL数据库的内容在网页的增删改写
- 1.建立项目
- 2.定义模型
- 3.创建视图
- 4.创建模板
- 5.创建表单和配置url
- 6.最后修改
- 7.效果
1.建立项目
输入命令django-admin startproject aaa 新建项目,项目名称命名为aaa,打开aaa文件夹,命令提示符输入python manage.py startapp TestModel新建名为TestModel的应用,接下来所有操作几乎都是在aaa/TestModel这个文件夹里完成
环境配置,python = 3.8.6
ansicon 1.89.0
arrow 1.2.3
asgiref 3.7.2
async-timeout 4.0.2
autopep8 1.7.0
backports.zoneinfo 0.2.1
bcrypt 3.2.0
beautifulsoup4 4.10.0
blessed 1.19.1
certifi 2021.10.8
cffi 1.15.0
charset-normalizer 2.0.12
click 8.1.3
colorama 0.4.6
concurrent-log-handler 0.9.24
contourpy 1.0.5
coverage 7.4.0
cryptography 37.0.0
cycler 0.11.0
decorator 5.1.1
Deprecated 1.2.13
Django 3.2.12
django-bootstrap3 21.2
django-cors-headers 3.13.0
django-crontab 0.7.1
django-filter 21.1
django-htmx 1.17.2
django-multiselectfield 0.1.12
django-picklefield 3.1
django-q 1.3.9
django-redis 5.2.0
django-silk 5.0.1
djangorestframework 3.13.1
dnspython 2.2.1
et-xmlfile 1.1.0
exceptiongroup 1.2.0
fonttools 4.37.3
func_timeout 4.3.5
gprof2dot 2022.7.29
greenlet 1.1.2
hikpi-backend-atvipc 0.1.7
hikpi-backend-isapi 0.11.0
hikpi-backend-networks 1.0
hikpi-hikrequest 0.6
hikpi-krapi 1.0.1
hikpi-univice-api 0.4
hiredis 2.0.0
idna 3.3
importlib-metadata 4.11.3
influxdb 5.3.1
iniconfig 2.0.0
install 1.3.5
iso8601 1.0.2
jedi 0.18.1
Jinja2 3.1.2
jinxed 1.3.0
kiwisolver 1.4.4
loguru 0.6.0
Markdown 3.3.6
MarkupSafe 2.1.1
matplotlib 3.6.0
mongoengine 0.24.2
msgpack 1.0.8
mysql-connector 2.2.9
mysql-connector-python 8.0.21
mysqlclient 2.2.4
ntplib 0.4.0
numpy 1.23.3
openpyxl 3.0.9
packaging 21.3
pandas 2.0.3
paramiko 2.10.4
parso 0.8.3
Pillow 9.2.0
pip 24.2
pluggy 1.3.0
portalocker 2.7.0
prometheus-writer 0.1.2
protobuf 3.15.0
psycopg2 2.9.5
py 1.11.0
pycodestyle 2.9.1
pycparser 2.21
pycryptodome 3.20.0
pymongo 4.3.2
PyMySQL 1.0.2
PyNaCl 1.5.0
pyparsing 3.0.8
PySocks 1.7.1
pytest 7.4.4
pytest-cov 4.1.0
python-dateutil 2.8.2
python-dotenv 0.20.0
python-snappy 0.6.1
pythonping 1.1.4
pytz 2021.3
pywin32 306
redis 3.5.3
requests 2.31.0
requests-toolbelt 0.9.1
retry 0.9.2
retrying 1.3.4
robotframework 5.0.1
ruff 0.0.261
schedule 1.2.1
setuptools 49.2.1
six 1.16.0
soupsieve 2.3.1
SQLAlchemy 2.0.23
sqlparse 0.4.2
tabulate 0.9.0
taos-ws-py 0.3.2
taospy 2.7.12
toml 0.10.2
tomli 2.0.1
tqdm 4.64.1
typing_extensions 4.8.0
tzdata 2023.3
urllib3 1.26.9
wcwidth 0.2.5
win32-setctime 1.1.0
wrapt 1.14.0
xmltodict 0.12.0
zipp 3.8.0
2.定义模型
路径:aaa/TestModel/models.py,类名就是将要新建立的表的名称,最终数据中生成的表的名称为app名称_类名
# 定义一个 Staff 模型,它将对应数据库中的职工信息表
from django.db import models
class Staff(models.Model):
name = models.CharField(max_length=100)
position = models.CharField(max_length=100)
department = models.CharField(max_length=100)
hire_date = models.DateField()
def __str__(self):
return self.name
数据库迁移
python manage.py makemigrations TestModel
python manage.py migrate TestModel
创建数据表
创建一个名为runoob的数据库,在数据库创建一个名为TestModel的数据表,具体可自行百度,创建好了之后是这样子的
mysql> use runoob;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_runoob |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| runoob_tbl |
| runoob_tbl1 |
| testmodel_staff |
+----------------------------+
3.创建视图
路径:aaa/TestModel/views.py
# 创建视图用于展示、添加、修改和删除职工信息:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Staff
from .forms import StaffForm
def staff_list(request):
staffs = Staff.objects.all()
return render(request, 'staff/staff_list.html', {'staffs': staffs})
def staff_detail(request, pk):
staff = get_object_or_404(Staff, pk=pk)
return render(request, 'staff/staff_detail.html', {'staff': staff})
def staff_new(request):
if request.method == "POST":
form = StaffForm(request.POST)
if form.is_valid():
staff = form.save(commit=False)
staff.save()
return redirect('staff_list')
else:
form = StaffForm()
return render(request, 'staff/staff_new.html', {'form': form})
def staff_edit(request, pk):
staff = get_object_or_404(Staff, pk=pk)
if request.method == "POST":
form = StaffForm(request.POST, instance=staff)
if form.is_valid():
form.save()
return redirect('staff_list')
else:
form = StaffForm(instance=staff)
return render(request, 'staff/staff_edit.html', {'form': form})
def staff_delete(request, pk):
staff = get_object_or_404(Staff, pk=pk)
if request.method == "POST":
staff.delete()
return redirect('staff_list')
return render(request, 'staff/staff_delete.html', {'staff': staff})
4.创建模板
主界面,路径:aaa/TestModel/templates/staff/staff_list.html
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
{% block content %}
<h1>职工信息列表</h1>
<a href="{% url 'staff_new' %}">新增职工</a>
<table >
<thead>
<tr>
<th>姓名</th>
<th>职位</th>
<th>部门</th>
<th>入职日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for staff in staffs %}
<tr>
<td>{{ staff.name }}</td>
<td>{{ staff.position }}</td>
<td>{{ staff.department }}</td>
<td>{{ staff.hire_date|date:"Y-m-d" }}</td>
<td>
<a href="{% url 'staff_detail' staff.pk %}">详情</a>
<a href="{% url 'staff_edit' staff.pk %}">编辑</a>
<a href="{% url 'staff_delete' staff.pk %}">删除</a>
</td>
</tr>
{% empty %}
<tr>
<td colspan="5">没有找到相应记录</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
详情界面,路径:aaa/TestModel/templates/staff/staff_detail.html
{% block title %}职工详情 - {{ staff.name }}{% endblock %}
{% block content %}
<h1>{{ staff.name }} 的详细信息</h1>
<p><strong>职位:</strong> {{ staff.position }}</p>
<p><strong>部门:</strong> {{ staff.department }}</p>
<p><strong>入职日期:</strong> {{ staff.hire_date|date:"Y-m-d" }}</p>
<a href="{% url 'staff_list' %}">返回职工列表</a>
{% endblock %}
新增界面,路径:aaa/TestModel/templates/staff/staff_new.html
{% block content %}
<h1>新增员工信息</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交</button>
</form>
{% endblock %}
编辑修改界面,路径:aaa/TestModel/templates/staff/staff_edit.html
{% block content %}
<h1>员工信息表单</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交</button>
</form>
{% endblock %}
删除界面,路径:aaa/TestModel/templates/staff/staff_delete.html
{% block content %}
<h1>确认删除</h1>
<p>你确定要删除员工 <strong>{{ employee.name }}</strong> 吗?</p>
<form method="post">
{% csrf_token %}
<button type="submit" class="delete-button">确认删除</button>
<a href="{% url 'staff_list' %}" class="cancel-button">取消</a>
</form>
{% endblock %}
5.创建表单和配置url
创建表单
路径:aaa/TestModel/forms.py
from django import forms
from .models import Staff
class StaffForm(forms.ModelForm):
class Meta:
model = Staff
fields = ('name', 'position', 'department', 'hire_date')
配置url
路径:aaa/TestModel/urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('', views.staff_list, name='staff_list'),
path('admin/', admin.site.urls),
path('staff/<int:pk>/', views.staff_detail, name='staff_detail'),
path('staff/new/', views.staff_new, name='staff_new'),
path('staff/<int:pk>/edit/', views.staff_edit, name='staff_edit'),
path('staff/<int:pk>/delete/', views.staff_delete, name='staff_delete'),
]
6.最后修改
配置应用,路径:aaa/TestModel/apps.py
from django.apps import AppConfig
class TestmodelConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'TestModel'
修改项目url,而不是应用url,路径:aaa/urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.hello),
path('staff/', include('TestModel.urls')),
]
修改项目设置,路径:aaa/settings.py
"""
Django settings for aaa project.
Generated by 'django-admin startproject' using Django 3.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^1ld4@-ti^qgd#p^rcdv1dj628bk@x%ima3e8a!n&kavpq!+06'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin', # admin管理后台站点
'django.contrib.auth', # 身份认证系统
'django.contrib.contenttypes', # 内容类型框架
'django.contrib.sessions', # 会话框架
'django.contrib.messages', # 消息框架
'django.contrib.staticfiles', # 静态文件管理框架
'TestModel', # 添加此项
]
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',
]
ROOT_URLCONF = 'aaa.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_APPLICATION = 'aaa.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'runoob', # 数据库名称
'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'Dcx0417*', # 数据库密码
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
########################################################################################################
STATIC_URL = '/static/' # 别名
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "statics"),
]
7.效果
总目录
输入运行命令:Python manage.py runserver
打开网址:http://127.0.0.1:8000/staff/
主界面
详情界面
编辑界面
删除界面
新增界面