从第2章开始,我们正式以实战为核心开发用户管理系统,计划实现效果图所有模块功能。
本章我们将开始实现我们第一个功能模块:用户管理。
Boostrap、jQuery、???Django
模块 | 进度 | 功能点 |
---|---|---|
部门管理 | 完成 | 增删改查,搜索,分页 |
用户管理 | 完成 | 增删改查,搜索,分页 |
认证 | 完成 | 登录/验证码/修改密码 |
数据统计 | 完成 | echarts折线图,柱状图,饼图 |
文件上传 | 完成 | 解析文件到db,form表单上传图片 |
基于mysite项目创建名为 ums 的app
python manage.py startapp ums
模板文件和静态文件分别放入templates和static文件夹,django会自动加载到容器。
如果你像放到其他位置可以在 settings.py 里面搜索template和static进行更改路径(非特殊需求不建议更改)。
在mysite/settings.py文件中配置你的MySQL连接信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ums',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '123456',
}
}
mysqlclient是django 数据库连接库,负责数据的操作和持久化,初始化表结构。
pip install mysqlclient
在 ums/models.py 放入以下内容
class UserInfo(models.Model):
username = models.CharField(verbose_name='用户名', max_length=32)
password = models.CharField(verbose_name='密码', max_length=64)
age = models.IntegerField(verbose_name='年龄')
salary = models.DecimalField(verbose_name='工资', max_digits=10, decimal_places=2)
gender_choices =(
(1, '男'),
(2, '女')
)
gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices)
create_time = models.DateTimeField(verbose_name='创建时间')
初始化表结构
$ python manage.py makemigrations
$ python manage.py migrate
在 ums/views.py 编写用户增删改查
def user_list(request):
""" 查询用户列表 """
# 获取所有用户列表 [obj,obj,obj]
queryset = models.UserInfo.objects.all()
return render(request, 'user_list.html', {'queryset': queryset})
def user_add(request):
""" 添加用户 """
if request.method == "GET":
context = {
'gender_choices': models.UserInfo.gender_choices,
"dept_list": models.Department.objects.all()
}
return render(request, 'user_add.html', context)
# 获取用户提交的数据
user = request.POST.get('username')
pwd = request.POST.get('pwd')
age = request.POST.get('age')
salary = request.POST.get('salary')
ctime = request.POST.get('ctime')
gender = request.POST.get('gd')
dept = request.POST.get('dp')
# 添加到数据库中
models.UserInfo.objects.create(username=user, password=pwd, age=age,
salary=salary, create_time=ctime,
gender=gender, dept_id=dept)
# 返回到用户列表页面
return redirect("/user/list/")
def user_delete(request, nid):
""" 删除用户 """
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/user/list/')
def user_edit(request, nid):
""" 编辑用户 """
row_object = models.UserInfo.objects.filter(id=nid).first()
if request.method == "GET":
# 根据ID去数据库获取要编辑的那一行数据(对象)
form = UserModelForm(instance=row_object)
return render(request, 'user_edit.html', {'form': form})
form = UserModelForm(data=request.POST, instance=row_object)
if form.is_valid():
# 默认保存的是用户输入的所有数据,如果想要再用户输入以外增加一点值
# form.instance.字段名 = 值
form.save()
return redirect('/user/list/')
return render(request, 'user_edit.html', {"form": form})
from django import forms
class UserModelForm(forms.ModelForm):
username = forms.CharField(min_length=3, label="用户名")
class Meta:
model = models.UserInfo
fields = ["username", "password", "age", 'salary', 'create_time', "gender", "dept"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环找到所有的插件,添加了class="form-control"
for name, field in self.fields.items():
field.widget.attrs = {"class": "form-control", "placeholder": field.label}
templates下编写模板
user_list.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px">
<a class="btn btn-success" href="/user/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建用户
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
用户列表
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>工资</th>
<th>创建时间</th>
<th>性别</th>
<th>所属部门</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}</th>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
<td>{{ obj.salary}}</td>
<td>{{ obj.create_time|date:"Y-m-d" }}</td>
<td>{{ obj.get_gender_display }}</td>
<td>{{ obj.dept.name}}</td>
<td>
<a class="btn btn-primary btn-xs" href="/user/{{ obj.id }}/edit/">编辑</a>
<a class="btn btn-danger btn-xs" href="/user/{{ obj.id }}/delete/">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
user_add.html?
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 新建用户 </h3>
</div>
<div class="panel-body">
<form method="post">
{% csrf_token %}
<div class="form-group">
<label>用户名</label>
<input type="text" class="form-control" placeholder="姓名" name="username" />
</div>
<div class="form-group">
<label>密码</label>
<input type="text" class="form-control" placeholder="密码" name="pwd"/>
</div>
<div class="form-group">
<label>年龄</label>
<input type="text" class="form-control" placeholder="年龄" name="age"/>
</div>
<div class="form-group">
<label>余额</label>
<input type="text" class="form-control" placeholder="工资" name="salary"/>
</div>
<div class="form-group">
<label>创建时间</label>
<input type="text" class="form-control" placeholder="创建时间" name="ctime"/>
</div>
<div class="form-group">
<label>性别</label>
<select class="form-control" name="gd">
{% for item in gender_choices %}
<option value="{{ item.0 }}">{{ item.1 }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label>部门</label>
<select class="form-control" name="dp">
{% for item in dept_list %}
<option value="{{ item.id }}">{{ item.name}}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
user_edit.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 编辑用户 </h3>
</div>
<div class="panel-body">
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}">
<style>
.navbar {
border-radius: 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
<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><a href="/user/list/">用户管理</a></li>
<li><a href="#">Link</a></li>
</ul>
<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">Johnny<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>
{% block content %}{% endblock %}
</div>
<script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}"></script>
</body>
</html>
在 mysite/urls.py 配置路由
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
# 用户管理
path('user/list/', views.user_list),
path('user/add/', views.user_add),
path('user/<int:nid>/edit/', views.user_edit),
path('user/<int:nid>/delete/', views.user_delete),
]
启动程序
python manage.py runserver
启动后,访问127.0.0.1:8000/user/list
需要完整源代码评论区留言:想要源码
如果本文对你有帮助,记得点赞+关注,你的支持是我最大的动力!