6.Djiango-部门管理

Django 员工管理系统

  • 创建项目
    django-admin startproject myproject
    django-admin startapp employee_management
  • 创建数据库、连接数据库
    • create database my_project DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  DATABASES = {
      'default':{
          'ENGINE':'django.db.backends.mysql',
          'NAME':'my_project',
          'USER':'root',
          'PASSWORD':'xxxxxx',
          'HOST':'127.0.0.1',
          'PORT':'3306',
      }
  }
  • 设计表结构

    from django.db import models
    # Create your models here.
    # 员工管理系统表
    class Department(models.Model):
      """部门表"""
      dep_id = models.IntegerField(verbose_name="部门代码", null=True, blank=True, unique=True)
      title = models.CharField(max_length=32, verbose_name='标题', null=True, blank=True, unique=True)
    
    class Employee(models.Model):
      """员工表"""
      name = models.CharField(max_length=16, verbose_name="姓名")
      password = models.CharField(max_length=64, verbose_name="密码")
      age = models.IntegerField(verbose_name="年龄")
      account = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
      create_time = models.DateField(verbose_name="入职时间")
    
      # 外键约束
      # to 表示与哪张表关联
      # to_field 表示表中的哪一列
      # 在django中,数据表中的名称自动加上_id,也就是depart_id
      # on_delete=models.CASCADE 表示级联删除(删除部门,部门下的所有员工都会被删除)
      depart = models.ForeignKey(to="Department", to_field="dep_id", on_delete=models.CASCADE, verbose_name="部门")
      # on_delete=models.SET_NULL, null=True, blank=True 表示置空(删除部门,部门下的所有员工的部门字段置为空)
      #depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.SET_NULL, null=True, blank=True)
    
      gender_choices = (
          (1, "男"),
          (2, "女"),
      )
      gender = models.SmallIntegerField(choices=gender_choices,verbose_name="性别")
    
    # INSERT INTO blog_department(dep_id,title) VALUES(101,'销售');
    # INSERT INTO blog_department(dep_id,title) VALUES(102,'运维');
    # INSERT INTO blog_employee(`name`,`password`,age,account,create_time,depart_id,gender) VALUE("tang","123321",18,10000,CURDATE(),102,1);
    # SELECT * FROM blog_employee e INNER JOIN blog_department d WHERE d.dep_id = e.depart_id
  • 生成数据库表
    python3 manage.py makemigrations
    python3 manage.py migrate
  • 样例数据
    INSERT INTO blog_department(title) VALUES('销售')
    INSERT INTO blog_department(title) VALUES('运维')
    INSERT INTO blog_employee(`name`,`password`,age,account,create_time,depart_id,gender) VALUE("tang","123321",18,10000,CURDATE(),2,1)
    INSERT INTO blog_department(title) VALUES('运维')
    SELECT * FROM blog_employee e INNER JOIN blog_department d WHERE d.id = e.depart_id

部门管理

  • 展示 depart_list.html

  def depart_list(req):
      depart_list = Department.objects.all().order_by("id")
      return render(req, 'depart_list.html', {"depart_list": depart_list})
  <table class="table table-bordered">
      <thead>
      <tr>
          <th>ID</th>
          <th>部门ID</th>
          <th>部门名称</th>
          <th>操作</th>
      </tr>
      </thead>
      <tbody>
      {% for iteam in depart_list %}
      <tr>
          <th scope="row">{{ iteam.id }}</th>
          <td>{{ iteam.dep_id }}</td>
          <td>{{ iteam.title }}</td>
          <td>
          <a class="btn btn-primary btn-xs" href="/depart/{{ iteam.id }}/edit/"> 编辑 </a>
          <a class="btn btn-danger btn-xs" href="/depart/del/?nid={{ iteam.id }}"> 删除 </a>
          </td>
      </tr>
      {% endfor %}
      </tbody>
  </table>
  • 新增 depart_add.html

  def depart_add(req):
      """部门添加"""
      if req.method == "GET":
          return render(req, "depart_add.html")

      try:
          # 获取用户提交的部门数据
          depart_id = req.POST.get("depart_id")
          depart_title = req.POST.get("depart_title")

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

          # 重定向回部门列表
          return redirect("/depart/list/")
      except Exception as e:
          # print(e)
          return render(req, "depart_add.html", {"error_msg": e})
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title"><strong>新建部门</strong></h3>
    </div>
    <div class="panel-body">
      <form class="form-inline" method="post" action="/depart/add/">
        {% csrf_token %}
        <div class="form-group">
          <label for="depart_add"><strong>部门ID:</strong></label>
          <input type="text" class="form-control" name="depart_id" style="width: 300px;" id="depart_add" placeholder="输入增加的部门ID">
        </div>
        <div class="form-group" style="margin-left: 20px;">
          <label for="depart_add"><strong>部门名称:</strong></label>
          <input type="text" class="form-control" name="depart_title" style="width: 300px;" id="depart_add" placeholder="输入增加的部门名称">
        </div>
        <div class="form-group" style="margin-left: 20px;">
          <button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span><strong> 提 交</strong></button>
        </div>
        <br>
        <span style="color: red;">  {{ error_msg }}  </span>
      </form>
    </div>
  </div>
  • 删除

  def depart_del(req):
      """部门删除"""
      # 获取想要删除的部门ID
      nid = req.GET.get("nid")

      # 操作数据库删除对应数据
      Department.objects.filter(id=nid).delete()

      # 重定向回部门列表
      return redirect("/depart/list/")
  <a class="btn btn-danger btn-xs" href="/depart/del/?nid={{ iteam.id }}"> 删除 </a>
  • 编辑 depart_edit.html

  def depart_edit(req, nid):
      """部门编辑"""
      # 获取想要编辑的部门ID
      if req.method == "GET":
          # 查询对应数据
          old_title = Department.objects.filter(id=nid).first()
          return render(req, "depart_edit.html", {"old_dep_id": old_title.dep_id, "old_title": old_title.title, "nid": nid})

      try:
          # 获取用户提交的部门数据
          depart_id = req.POST.get("depart_id")
          depart_title = req.POST.get("depart_title")

          # 修改对应数据
          Department.objects.filter(id=nid).update(dep_id=depart_id, title=depart_title)

          # 重定向回部门列表
          return redirect("/depart/list/")
      except Exception as e:
          # print(e)
          return render(req, "depart_edit.html", {"error_msg": e})
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title"><strong>修改部门</strong></h3>
    </div>
    <div class="panel-body">
      <form class="form-inline" method="post" action="/depart/{{ nid }}/edit/">
        {% csrf_token %}
        <div class="form-group">
          <label for="depart_add"><strong>部门ID:</strong></label>
          <input type="text" class="form-control" name="depart_id" style="width: 300px;" id="depart_add" placeholder="{{ old_dep_id }}">
        </div>
        <div class="form-group" style="margin-left: 20px;">
          <label for="depart_add"><strong>部门名称:</strong></label>
          <input type="text" class="form-control" name="depart_title" style="width: 300px;" id="depart_edit" placeholder="{{ old_title }}">
        </div>
        <div class="form-group" style="margin-left: 20px;"></div>
          <button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span><strong> 提 交</strong></button>
        </div>
        <br>
        <span style="color: red;">  {{ error_msg }}  </span>
      </form>
    </div>