员工管理系统 - 部门管理、用户管理

1. 创建项目

django-admin startproject employeeManage

2. 创建APP

python manage.py startapp app01

2.1 注册APP(settings.py)

INSTALLED_APPS = [
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

3. 设计表结构

  • 关联表(用户表关联部门表)

    • ID;数据库范式(理论知识),常见开发都是这样;【节省存储开销】
    • 名称;特别大的公司;查询的次数非常多,连表操作比较耗时;【为了加速查找,允许数据冗余】
  • 对部门ID进行约束

    • 只能是部门表中已存在的ID
  • 如果部门被删除,关联的用户

    • 删除用户 – 级联删除
    • 部门ID列置空
from django.db import models

# Create your models here.

class Department(models.Model):
    """ 部门表 """
    titel = models.CharField(verbose_name="部门名称", max_length=32)

class UserInfo(models.Model):
    """ 员工表 """
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄")
    account_salary = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_date = models.DateTimeField(verbose_name="入职时间")

    # 无约束
    # did = models.BigIntegerField(verbose_name="部门ID")

    # 1. 有约束 [to:与哪张表关联] [to_field:与哪一列进行关联]
    # 2. django自动;写的depart;生成数据列 depart_id
    # 3. 部门表删除行
    # 3.1 用户表级联删除
    depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
    # 3.2 部门表删除行,用户表绑定数据置空
    # depart = models.ForeignKey(to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)

    # 在Django中做的约束
    gender_choices = (
        (1, "男"),
        (2, "女"),
    )
    gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)

4. 在MySQL中生成表

  • 工具链接MySQL生成数据库
create database 数据库名称 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • 修改配置文件连接MySQL
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",   # 数据库类型
        "NAME": "djangotest03",                 # 数据库名称
        "USER": "root",                         # 用户名
        "PASSWORD": "root123",                  # 密码
        "HOST": "127.0.0.1",                    # 主机
        "PORT": "3306",                         # 端口
    }
}
  • django命令生成数据库表
python manage.py makemigrations
python manage.py migrate

5. 静态文件管理

  • 创建静态文件文件夹templates

6.部门管理

体验;Django中提供Form和ModelForm组件(方便)

6.1 部门列表

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="{% static 'plugins/bootstrap-3.4.1-dist/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="/depart/list/">部门管理</a></li>
            <li><a href="#">用户管理</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"
                >徐泽林 <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>
      <div class="container">
        <div style="margin-bottom: 20px;">
            <a href="#" class="btn btn-success">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建部门
            </a>
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">
                <span class="glyphicon glyphicon-list" aria-hidden="true"></span>
                部门列表
            </div>
      
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>部门名称</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th scope="row">1</th>
                  <td>销售部</td>
                  <td>
                    <a href="#" class="btn btn-primary btn-xs">编辑</a>
                    <a href="#" class="btn btn-danger btn-xs">删除</a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
      </div>
    </div>

    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
  </body>
</html>
from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('depart/list/', views.depart_list),
]
def depart_list(request):
    """ 部门列表 """

    # 1.去数据库中获取所有的部门信息
    # queryset:是一个列表,列表中放的是一个一个的对象;对象中封装了一行数据;
    queryset = models.Department.objects.all()

    return render(request, 'depart_list.html', {'queryset':queryset})

6.2 添加部门

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="{% static 'plugins/bootstrap-3.4.1-dist/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="/depart/list/">部门管理</a></li>
            <li><a href="#">用户管理</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"
                >徐泽林 <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>
      <div class="container">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">新建部门</h3>
          </div>
          <div class="panel-body">
            <form>
              <div class="form-group">
                <label>部门名称</label>
                <input
                  type="text"
                  class="form-control"
                  placeholder="请输入内容"
                  name="title"
                />
              </div>

              <button type="submit" class="btn btn-primary">提 交</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
  </body>
</html>
def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request, 'depart_add.html')
    # 获取用户通过POST方式提交过来的数据
    depart_title = request.POST.get('title')

    # 保存到数据库
    models.Department.objects.create(title = depart_title)

    # 重定向回到部门列表页面
    return redirect('/depart/list/')

6.3 删除部门

<tbody>
              {% for obj in queryset %}
              
                {{ obj.id }}
                {{ obj.title }}
                
                  编辑
                  删除
                
              
              {% endfor %}
            </tbody>
def depart_delete(request):
    """ 删除部门"""

    # 获取ID
    nid = request.GET.get('id')
    # 删除
    models.Department.objects.filter(id=nid).delete()
    # 跳转回部门列表
    return redirect('/depart/list/')

6.4 修改部门

path('depart/<int:nid>/edit/', views.depart_edit),
def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == 'GET':
        # 根据nid获取他的这一行数据
        row_object = models.Department.objects.filter(id=nid).first()
        # print(row_object.id, row_object.title)

        return render(request, 'depart_edit.html', {'row_object':row_object})

    models.Department.objects.filter(id=nid).update(title=request.POST.get('title'))
    return redirect('/depart/list/')
<div>
  <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="title"
              value="{{row_object.title}}"
            />
          </div>

          <button type="submit" class="btn btn-primary">保 存</button>
        </form>
      </div>
    </div>
  </div>
</div>
<tbody>
  {% for obj in queryset %}
  
    {{ obj.id }}
    {{ obj.title }}
    
      编辑
      删除
    
  
  {% endfor %}
</tbody>

7. 模板的继承

  • 部门列表
  • 添加部门
  • 编辑部门
def user_list(request):
    """ 用户管理 """

    # 获取所有用户信息
    queryset = models.UserInfo.objects.all()
    # for obj in queryset:
    #     print(obj.name, obj.password, obj.id, obj.account_salary, obj.create_date.strftime('%Y-%m-%d'), obj.get_gender_display(), obj.depart.title)
        # obj.gender # 1/2
        # get_字段名称_display() 男/女
        # obj.get_level_display()
        # obj.depart_id 获取数据库中存储的那个字段值
        # obj.depart.title # 根据ID自动去关联的表中获取那一行数据depart对象

    return render(request, 'user_list.html', {'queryset':queryset})
  • 原始方法
  def user_add(request):
      """ 添加用户(原始方式) """
      
      if request.method == "GET":
          context = {
              'gender_choices': models.UserInfo.gender_choices,
              'depart_list': models.Department.objects.all(),
          }
          return render(request, 'user_add.html', context)
  
      # 获取用户提交的数据
      user = request.POST.get('user')
      pwd = request.POST.get('pwd')
      age = request.POST.get('age')
      account = request.POST.get('ac')
      ctime = request.POST.get('ctime')
      gender = request.POST.get('gd')
      depart_id = request.POST.get('dp')
  
      # 添加到数据库
      models.UserInfo.objects.create(
          name=user,
          password=pwd,
          age=age,
          account_salary=account,
          create_date=ctime,
          gender=gender,
          depart_id=depart_id
      )
      return redirect('/user/list/')
  • Form
class MyForm(Django中的Form):
    user = forms.CharField(widget=forms.Input)
    pwd = form.CharFiled(widget=forms.Input)
    email = form.CharFiled(widget=forms.Input)
    account = form.CharFiled(widget=forms.Input)
    create_time = form.CharFiled(widget=forms.Input)
    depart = form.CharFiled(widget=forms.Input)
    gender = form.CharFiled(widget=forms.Input)
    
    
def user_add(request):
    
    if request.method == "GET":
        form = MyForm()
        return render(request, 'user_add.html', {"form":form})
  • modelform
class UserInfo(models.Model):
    """ 员工表 """
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄")
    account_salary = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_date = models.DateTimeField(verbose_name="入职时间")
    depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
    gender_choices = (
        (1, "男"),
        (2, "女"),
    )
    gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)
class MyForm(ModelForm):
    xx = form.CharField*("...")
    class Meta:
        model = UserInfo
        fields = ["name", "password", "age", "xx"]
    
    
def user_add(request):
    
    if request.method == "GET":
        form = MyForm()
        return render(request, 'user_add.html', {"form":form})

8. 添加用户(ModelForm)

# ########################### ModelForm 示例 ###########################
from django import forms
class UserModelForm(forms.ModelForm):

    name = forms.CharField(min_length=3, label="姓名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "gender", "age", "account_salary", "password", "depart", "create_date"]
        # widgets = {
        #     'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'请输入内容'}),
        #     'password': forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'请输入内容'}),
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': '请输入内容'}
        

def user_model_form_add(request):
    """ 添加用户(ModelForm版本) """

    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form':form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法,保存到数据库
        form.save()
        return redirect('/user/list/')
    # 校验失败(页面上显示错误信息)
    return render(request, 'user_model_form_add.html', {'form':form})
  • 剩余内容需见项目DjangoTest02 或 本地文件

评论