联通用户管理系统(一)

#联通用户管理系统(一)

1.新建项目

如果你是windows的话,界面应该是如下的:

2.创建app

python manage.py startapp app01

一般情况下:我们是在pycharm的终端中运行上述指令,但是pychrm中为我们提供了工具,点击工具,找到并点击Run manage.py Task,便打开了manage.py窗口,相当于pychrm为我们运行了manage.py。我们直接输入startapp app01 便可以出创建app了。

如果你是windows电脑,界面如下:

注册app:将我们创建的app注册到setting.py中

3.设计表结构(django)

python 复制代码
from django.db import models


class Department(models.Model):
    """ 部门表 """
    title = 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 = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_time = models.DateTimeField(verbose_name="入职时间")

    # 无约束
    # depart_id = 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 gx_day16 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
    
  • 修改配置文件,连接MySQL

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'gx_day16',  # 数据库名字
            'USER': 'root',
            'PASSWORD': 'root123',
            'HOST': '127.0.0.1',  # 那台机器安装了MySQL
            'PORT': 3306,
        }
    }
    
  • django命令生成数据库表

    python manage.py makemigrations
    python manage.py migrate
    

如果你在测试连接数据库的过程中出现错误,可以先检查settings.py文件中MYSQL数据库的配置是否正确。

表结构创建成功:

5.静态文件管理

static目录

6.部门管理

我们先用最原始的方式来做,之后我们再用dgango组件

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

在还没有创建新建部门的功能时,为了数据是否能够显示,可以进行如下操作:

通过Dgano Shell插入数据

在Dgango项目的根目录下,打开终端,使用命令进入Django Shell:

base 复制代码
python manage.py shell

然后运行以下代码插入部门数据:

python 复制代码
from app01.models import Department
# 创建部门数据
Department.objects.creat(title="人事部")
Department.objects.creat(title="技术部")
Department.objects.creat(title="财务部")

这会 将部门数据插入到department表中。

models.py

python 复制代码
from django.db import models

# 部门管理
class Department(models.Model):
    """部门表"""
    #id = models.BigAutoField(verbose_name="ID", primary_key=True)
    title = models.CharField(verbose_name="标题", max_length=32,null="True",blank="True")

class UsrInfo(models.Model):
    """员工表"""
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄", default=0)
    account = models.DecimalField(verbose_name="账户余额",max_digits=10,decimal_places=2,default=0)

    create_time = models.DateTimeField(verbose_name="入职时间")
    # #无约束的
    # depart_id = 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.CASCADE)

    # 在django中做约束 男女
    gender_choices =(
        (1, '男'),
        (2,'女'),
    )

    gender_choices = models.SmallIntegerField(verbose_name="性别",choices=gender_choices)

urls.py

python 复制代码
"""
URL configuration for Employee_Management_System project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
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),
    # 添加部门
    path('depart/add/',views.depart_add),

    #删除部门
    path('depart/delete/',views.depart_delete),

    # 编辑部门
    path('depart/<int:nid>/edit/',views.depart_edit)



]

views.py

python 复制代码
from django.shortcuts import render, redirect
from app01 import models
# Create your views here.
def depart_list(request):
    """部门列表"""

    #却数据库中获取部门信息
    queryset = models.Department.objects.all()
    return render(request,'depart_list.html',{'queryset':queryset})

def depart_add(request):
    """添加部门"""
    if request.method == "GET":
        return render(request,'depart_add.html')
    # 获取用户通过post提交的是数据集
    title = request.POST.get("title")
    # 保存到数据库
    models.Department.objects.create(title=title)
    #重定项回部门列表
    return redirect("/depart/list/")

def depart_delete(request):
    """"删除部门"""
    # 获取id
    nid = request.GET.get('nid')
    # 删除
    models.Department.objects.filter(id=nid).delete()
    # 跳转
    return redirect("/depart/list/")

def depart_edit(request,nid):
    """编辑部门"""
    if request.method == "GET":
        #根据nid获取数据
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request,'depart_edit.html',{'row_object':row_object})

    #获取用户提交的标题,根据id找到数据库中的数据并进行更新
    models.Department.objects.filter(id=nid).update(title=request.POST.get("title"))

    #重新定向会部门列表
    return redirect("/depart/list/")

depart_list.html

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: 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="#">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">橙子师兄 <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: 10px">
            <a class="btn btn-success" href="/depart/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>
          </tr>
        </thead>
        <tbody>
        {% for obj in queryset %}
          <tr>
            <th>{{ obj.id }}</th>
            <td>{{ obj.title }}</td>
            <td>
                <a class="btn btn-primary btn-xs" href="/depart/{{ obj.id }}/edit/">编辑</a>
                <a class="btn btn-danger btn-xs" href="/depart/delete/?nid={{ obj.id }}">删除</a>
            </td>
          </tr>
        {% endfor %}
        </tbody>
      </table>
    </div>
</div>
    </div>



</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>

depart_add.html

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: 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="#">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">橙子师兄 <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 method="post">
                    {% csrf_token %}
                  <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.6.0.min.js' %}"></script>
    <script src="{%  static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}"></script>

</body>
</html>

depart_edit.html

python 复制代码
{% 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: 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="#">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">橙子师兄 <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 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>

    <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>

效果展示:

7.模板的继承

  • 部门列表
  • 添加部门
  • 编辑部门

定义目版:layout.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugin...min.css' %}">
    {% block css %}{% endblock %}
</head>
<body>
    <h1>标题</h1>
    <div>
        {% block content %}{% endblock %}
    </div>
    <h1>底部</h1>
    
    <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
    {% block js %}{% endblock %}
</body>
</html>

继承母版:

html 复制代码
{% extends 'layout.html' %}

{% block css %}
	<link rel="stylesheet" href="{% static 'pluxxx.css' %}">
	<style>
		...
	</style>
{% endblock %}


{% block content %}
    <h1>首页</h1>
{% endblock %}


{% block js %}
	<script src="{% static 'js/jqxxxin.js' %}"></script>
{% endblock %}

8.用户管理

sql 复制代码
insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id) values("韩超","666",23,100.68,"2020-01-11",2,1);

insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id) values("刘东","123",23,100.68,"2010-11-11",1,4);

insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id) values("朱虎飞","999",33,9900.68,"2021-05-11",1,1);
+-------------+---------------+------+-----+---------+----------------+
| Field       | Type          | Null | Key | Default | Extra          |
+-------------+---------------+------+-----+---------+----------------+
| id          | bigint(20)    | NO   | PRI | NULL    | auto_increment |
| name        | varchar(16)   | NO   |     | NULL    |                |
| password    | varchar(64)   | NO   |     | NULL    |                |
| age         | int(11)       | NO   |     | NULL    |                |
| account     | decimal(10,2) | NO   |     | NULL    |                |
| create_time | datetime(6)   | NO   |     | NULL    |                |
| gender      | smallint(6)   | NO   |     | NULL    |                |
| depart_id   | bigint(20)    | NO   | MUL | NULL    |                |
+-------------+---------------+------+-----+---------+----------------+

新建用户:

  • 原始方式理思路:不会采用(本质)【麻烦】

    - 用户提交数据没有校验。
    - 错误,页面上应该有错误提示。
    - 页面上,没一个字段都需要我们重新写一遍。     [OK]
    - 关联的数据,手动去获取并展示循环展示在页面。  [OK]
    
  • Django组件

    • Form组件(小简便)
    • ModelForm组件(最简便)

8.1 初识Form

1. views.py
python 复制代码
class MyForm(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})
2.user_add.html
html 复制代码
<form method="post">
    {% for field in form%}
    	{{ field }}
    {% endfor %}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>
html 复制代码
<form method="post">
    {{ form.user }}
    {{ form.pwd }}
    {{ form.email }}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>

8.3 ModelForm(推荐)

0. models.py
python 复制代码
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 = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_time = 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)
1. views.py
python 复制代码
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})
2.user_add.html
html 复制代码
<form method="post">
    {% for field in form%}
    	{{ field }}
    {% endfor %}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>
html 复制代码
<form method="post">
    {{ form.user }}
    {{ form.pwd }}
    {{ form.email }}
    <!-- <input type="text"  placeholder="姓名" name="user" /> -->
</form>
相关推荐
迅翼SwiftWing21 分钟前
迅翼SwiftWing | ROS 固定翼开源仿真平台正式发布!
python·开源·无人机
九河云34 分钟前
阿里云数据传输服务使用场景
数据库·阿里云·云计算
桂月二二44 分钟前
深入探索Vue.js 3中基于Composition API的动态组件开发
前端·javascript·vue.js
我不爱机器学习1 小时前
基于pysptools实现端元提取及无监督光谱分类
python
_.Switch1 小时前
高效构建与部署Python Web应用:FastAPI的测试与持续集成
前端·网络·数据库·python·ci/cd·fastapi
游客5201 小时前
自动化办公|将Excel导出为PDF
python·pdf·自动化·excel
大家的林语冰2 小时前
联手 AI 给 Vue 和 Vite 贡献源码,我学到了什么?
前端·javascript·豆包marscode
不烦下雨c2 小时前
【Mysql进阶知识】Mysql 程序的介绍、选项在命令行配置文件的使用、选项在配置文件中的语法
数据库·mysql
该用户已存在(真)2 小时前
python循环结构(for)
笔记·python