本文主要是介绍Django项目实战之后台员工信息管理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 本页面完成项目后台管理的员工模块操作
(1). 员工信息数据表:user
- 在数据库
osdb
中创建user表,若此表已存在请跳过
-- 员工信息表
CREATE TABLE `user` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '员工账号id',`username` varchar(50) DEFAULT NULL COMMENT '员工账号',`nickname` varchar(50) DEFAULT NULL COMMENT '昵称',`password_hash` varchar(100) DEFAULT NULL COMMENT '密码',`password_salt` varchar(50) DEFAULT NULL COMMENT '密码干扰值',`status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '状态:1正常/2禁用/9删除',`create_at` datetime DEFAULT NULL COMMENT '创建时间',`update_at` datetime DEFAULT NULL COMMENT '修改时间',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
(2). 定义模型Model类
- 进入
myadmin
应用目录中编辑:myobject/myadmin/models.py
模型文件
from django.db import models
from datetime import datetime#员工账号信息模型
class User(models.Model):username = models.CharField(max_length=50) #员工账号nickname = models.CharField(max_length=50) #昵称password_hash = models.CharField(max_length=100)#密码password_salt = models.CharField(max_length=50) #密码干扰值status = models.IntegerField(default=1) #状态:1正常/2禁用/9删除create_at = models.DateTimeField(default=datetime.now) #创建时间update_at = models.DateTimeField(default=datetime.now) #修改时间def toDict(self):return {'id':self.id,'username':self.username,'nickname':self.nickname,'password_hash':self.password_hash,'password_salt':self.password_salt,'status':self.status,'create_at':self.create_at.strftime('%Y-%m-%d %H:%M:%S'),'update_at':self.update_at.strftime('%Y-%m-%d %H:%M:%S')}class Meta:db_table = "user" # 更改表名
(3). 项目urls路由信息配置
- 打开根路由文件:myobject/myadmin/urls.py路由文件,编辑路由配置信息
from django.urls import pathfrom myadmin.views import index
from myadmin.views import userurlpatterns = [# 后台首页path('', index.index, name="myadmin_index"),#员工账号信息管理path('user/<int:pIndex>', user.index, name="myadmin_user_index"),#浏览信息path('user/add', user.add, name="myadmin_user_add"), #加载添加表单path('user/insert', user.insert, name="myadmin_user_insert"), #执行信息添加path('user/del/<int:uid>', user.delete, name="myadmin_user_del"),#删除信息path('user/edit/<int:uid>', user.edit, name="myadmin_user_edit"),#准备信息编辑path('user/update/<int:uid>', user.update, name="myadmin_user_update"),#执行信息编辑#重置员工密码#path('user/resetpass/<int:uid>', user.resetpass, name="myadmin_user_resetpass"), #path('user/doresetpass/<int:uid>', user.doresetpass, name="myadmin_user_doresetpass"),]
(4). 编辑视图文件
- 创建:myobject/myadmin/views/user.py 视图文件,并进行编辑
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.db.models import Q
from django.core.paginator import Paginator
from datetime import datetime
import randomfrom myadmin.models import Userdef index(request,pIndex=1):'''浏览信息'''umod = User.objectsmywhere=[]list = umod.filter(status__lt=9)# 获取、判断并封装关keyword键搜索kw = request.GET.get("keyword",None)if kw:# 查询员工账号或昵称中只要含有关键字的都可以list = list.filter(Q(username__contains=kw) | Q(nickname__contains=kw))mywhere.append("keyword="+kw)# 获取、判断并封装状态status搜索条件status = request.GET.get('status','')if status != '':list = list.filter(status=status)mywhere.append("status="+status)#执行分页处理pIndex = int(pIndex)page = Paginator(list,5) #以5条每页创建分页对象maxpages = page.num_pages #最大页数#判断页数是否越界if pIndex > maxpages:pIndex = maxpagesif pIndex < 1:pIndex = 1list2 = page.page(pIndex) #当前页数据plist = page.page_range #页码数列表#list2 = User.objects.all() #获取所有信息#封装信息加载模板输出context = {"userlist":list2,'plist':plist,'pIndex':pIndex,'maxpages':maxpages,'mywhere':mywhere}return render(request,"myadmin/user/index.html",context)def add(request):'''加载添加页面'''return render(request,"myadmin/user/add.html")def insert(request):'''执行添加'''try:ob = User()ob.username = request.POST['username']ob.nickname = request.POST['nickname']#获取密码并md5import hashlibmd5 = hashlib.md5()n = random.randint(100000, 999999)s = request.POST['password']+str(n) md5.update(s.encode('utf-8'))ob.password_hash = md5.hexdigest()ob.password_salt = nob.status = 1ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")ob.save()context={"info":"添加成功!"}except Exception as err:print(err)context={"info":"添加失败"}return render(request,"myadmin/info.html",context)def delete(request,uid):'''删除信息'''try:ob = User.objects.get(id=uid)ob.status = 9ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")ob.save()context={"info":"删除成功!"}except Exception as err:print(err)context={"info":"删除失败"}return JsonResponse(context)#return render(request,"myadmin/info.html",context)def edit(request,uid):'''加载编辑信息页面'''try:ob = User.objects.get(id=uid)context={"user":ob}return render(request,"myadmin/user/edit.html",context)except Exception as err:context={"info":"没有找到要修改的信息!"}return render(request,"myadmin/info.html",context)def update(request,uid):'''执行编辑信息'''try:ob = User.objects.get(id=uid)ob.nickname = request.POST['nickname']ob.status = request.POST['status']ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")ob.save()context={"info":"修改成功!"}except Exception as err:print(err)context={"info":"修改失败"}return render(request,"myadmin/info.html",context)"""
def resetpass(request,uid):'''加载重置会员密码信息页面'''try:ob = User.objects.get(id=uid)context={"user":ob}return render(request,"myadmin/user/resetpass.html",context)except Exception as err:context={"info":"没有找到要修改的信息!"}return render(request,"myadmin/info.html",context)def doresetpass(request,uid):'''执行编辑信息'''try:ob = User.objects.get(id=uid)#获取密码并md5import hashlibmd5 = hashlib.md5()n = random.randint(100000, 999999)s = request.POST['password']+str(n) md5.update(s.encode('utf-8'))ob.password_hash = md5.hexdigest()ob.password_salt = nob.save()context={"info":"密码重置成功!"}except Exception as err:print(err)context={"info":"密码重置失败"}return render(request,"myadmin/info.html",context)
"""
(5). 编写模板文件
- 5.1. 后台用户信息浏览模板:/templates/myadmin/user/index.html
{% extends "myadmin/base.html" %}{% block main_body %}<!-- Content Header (Page header) --><section class="content-header"><h1>账号管理<small>订餐系统后台管理</small></h1><ol class="breadcrumb"><li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li><li class="active">员工账号信息管理</li></ol></section><!-- Main content --><section class="content container-fluid"><div class="row"><div class="col-xs-12"><div class="box"><div class="box-header"><h4 class="box-title"><i class="fa fa-calendar"></i> 员工账号信息表</h4><div class="box-tools"><form action="{% url 'myadmin_user_index' 1 %}" method="get"><div class="input-group input-group-sm" style="width:150px;"><input type="text" name="keyword" class="form-control pull-right" placeholder="账号/昵称"><div class="input-group-btn"><button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button></div></div></form></div></div><!-- /.box-header --><div class="box-body table-responsive no-padding"><table class="table table-hover"><tr><th>ID</th><th>员工账号</th><th>昵称</th><th>当前状态</th><th>添加时间</th><th>修改时间</th><th>操作</th></tr>{% for vo in userlist %}<tr><td>{{ vo.id }}</td><td>{{ vo.username }}</td><td>{{ vo.nickname }}</td><td>{% if vo.status == 1 %}<span style="color:green">正常</span>{% elif vo.status == 2 %}<span style="color:red">禁停</span>{% elif vo.status == 6 %}<span style="color:red">管理员</span>{% elif vo.status == 9 %}<span style="color:red">已删除</span>{% else %}<span style="color:red">未知状态</span>{% endif %}</td><td width="15%">{{ vo.create_at|date:'Y-m-d H:i:s' }}</td><td width="15%">{{ vo.update_at|date:'Y-m-d H:i:s' }}</td><td width="22%"><a href="{% url 'myadmin_user_edit' vo.id %}" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 编辑</a><button type="button" onclick="doDelete('{% url 'myadmin_user_del' vo.id %}')" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除</button><a type="button" class="btn btn-warning btn-xs"><span class="glyphicon glyphicon-search" aria-hidden="true"></span> 分配店铺</a></td></tr>{% endfor %}</table></div><!-- /.box-body --><div class="box-footer clearfix"><a role="button" href="{% url 'myadmin_user_add' %}" class="btn btn-primary btn-xs"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 添加会员</a><ul class="pagination pagination-sm no-margin pull-right"><li><a href="{% url 'myadmin_user_index' pIndex|add:-1 %}">«</a></li>{% for p in plist %}<li {% if p == pIndex %}class="active"{% endif %}><a href="{% url 'myadmin_user_index' p %}">{{p}}</a></li>{% endfor %}<li><a href="{% url 'myadmin_user_index' pIndex|add:1 %}">»</a></li></ul></div></div><!-- /.box --></div></div></section><!-- /.content -->
{% endblock %}
- 5.3. 后台用户信息添加模板:/templates/myadmin/user/add.html
{% extends "myadmin/base.html" %}{% block main_body %}<!-- Content Header (Page header) --><section class="content-header"><h1>账号管理<small>订餐系统后台管理</small></h1><ol class="breadcrumb"><li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li><li class="active">员工账号信息管理</li></ol></section><!-- Main content --><section class="content container-fluid"><div class="row"><div class="col-xs-12"><div class="box"><div class="box-header"><h2 class="box-title"><span class="glyphicon glyphicon-calendar" aria-hidden="true">添加员工账号信息</h2></div><!-- /.box-header --><!-- form start --><form class="form-horizontal" action="{% url 'myadmin_user_insert' %}" method="post">{% csrf_token %}<div class="box-body"><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">员工账号:</label><div class="col-sm-4"><input type="text" name="username" class="form-control" id="inputText1" placeholder="员工账号" /></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">昵称:</label><div class="col-sm-4"><input type="text" name="nickname" class="form-control" id="inputText2" placeholder="昵称" /></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">密码:</label><div class="col-sm-4"><input type="password" name="password" class="form-control" id="inputPassword1" /></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">重复密码:</label><div class="col-sm-4"><input type="password" name="repassword" class="form-control" id="inputPassword2" /></div></div></div><!-- /.box-body --><div class="box-footer"><div class="col-sm-offset-2 col-sm-10"><button type="submit" class="btn btn-primary">提交</button> <button type="reset" class="btn btn-default">重置</button><div class="col-sm-offset-2 col-sm-10"></div><!-- /.box-footer --></form></div><!-- /.box --></div></div></section><!-- /.content -->
{% endblock %}
- 信息提示页:/templates/myadmin/info.html
{% extends "myadmin/base.html" %}{% block main_body %} <!-- Content Header (Page header) --><section class="content-header"><h4>信息提示:</h4></section><div class="pad margin no-print"><div class="callout callout-info" style="margin-bottom: 0!important;padding-left: 50px"><h3><i class="fa fa-exclamation-triangle"></i> {{ info }}</h3></div></div>
{% endblock %}
- 5.4. 后台用户信息编辑模板:/templates/myadmin/users/edit.html
{% extends "myadmin/base.html" %}{% block main_body %}<!-- Content Header (Page header) --><section class="content-header"><h1>账号管理<small>订餐系统后台管理</small></h1><ol class="breadcrumb"><li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li><li class="active">员工账号信息管理</li></ol></section><!-- Main content --><section class="content container-fluid"><div class="row"><div class="col-xs-12"><div class="box"><div class="box-header"><h2 class="box-title"><span class="glyphicon glyphicon-calendar" aria-hidden="true">员工信息修改</h2></div><!-- /.box-header --><!-- form start --><form class="form-horizontal" action="{% url 'myadmin_user_update' user.id %}" method="post">{% csrf_token %}<div class="box-body"><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">员工账号:</label><div class="col-sm-4"><input type="text" name="username" value="{{user.username}}" class="form-control" disabled readonly id="inputText1" placeholder="员工账号" /></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">昵称:</label><div class="col-sm-4"><input type="text" name="nickname" value="{{user.nickname}}" class="form-control" id="inputText2" placeholder="昵称" /></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">添加时间:</label><div class="col-sm-4">{{ user.create_at|date:'Y-m-d H:i:s' }}</div></div><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">修改时间:</label><div class="col-sm-4">{{ user.update_at|date:'Y-m-d H:i:s' }}</div></div><div class="form-group"><label class="col-sm-2 control-label">当前状态:</label><div class="controls"> <input type="radio" name="status" class="input-xlarge" value="1" {% if user.status == 1 %}checked{% endif %} /> 正常 <input type="radio" name="status" class="input-xlarge" value="2" {% if user.status == 2 %}checked{% endif %} /> 禁用 <input type="radio" name="status" class="input-xlarge" value="6" {% if user.status == 6 %}checked{% endif %} /> 管理员</div></div></div><!-- /.box-body --><div class="box-footer"><div class="col-sm-offset-2 col-sm-10"><button type="submit" class="btn btn-primary">保存</button> <button type="reset" class="btn btn-default">重置</button><div class="col-sm-offset-2 col-sm-10"></div><!-- /.box-footer --></form></div><!-- /.box --></div></div></section><!-- /.content -->
{% endblock %}
⑥ 运行测试
- 在项目根目录下启动服务,并使用浏览器访问测试:http://localhost:8000/myadmin
[root@localhost myobject]# pwd
/python/myobject
[root@localhost myobject]# ls
manage.py myadmin myobject myweb static templates
[root@localhost myobject]# python manage.py runserver
Performing system checks...System check identified no issues (0 silenced).April 06, 2020 - 14:29:36
Django version 1.11, using settings 'myobject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C[root@localhost myobject]#
这篇关于Django项目实战之后台员工信息管理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!