IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Django学习-武沛齐教程【day2】 -> 正文阅读

[Python知识库]Django学习-武沛齐教程【day2】

员工管理系统

新建项目

django-admin startproject manage

django-admin startapp app01

运行项目:python manage.py runserver

注册app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config', # 添加app01
]

设计表结构

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)
    pwd = 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.DateField(verbose_name="入职时间")
    # #部门被删除,员工置空
    # depart = models.ForeignKey(
    #     to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)
    # 部门被删除,员工级联删除
    depart = models.ForeignKey(
        to="Department", to_field="id", on_delete=models.CASCADE)
    gender_choices=(
        (1,"男"),
        (2,"女")
    )
    # 只能选择1、2
    gender=models.SmallIntegerField(verbose_name="性别",choices=gender_choices)

MYsql生成表

创建数据库

create database manage default charset utf8 collate utf8_general_ci;

在mysite/settings.py中进行配置和修改

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test', #数据库的名字
        'HOST': '127.0.0.1', #数据库地址
        'PORT': '3306', #端口
        'USER': 'root', #用户名
        "PASSWORD": 'root123456', #密码
    }
}

命令行执行:

python manage.py makemigrations

python manage.py migrate

静态文件和模版文件管理

app01中添加static、templates目录

部门管理

手动插入数据

insert into app01_department(title) values("IT部"),("销售部");

部门列表

  • urls.py
urlpatterns = [
    path('depart/list/',views.depart_list),
]

  • views.py
from django.shortcuts import render
from app01 import models

def depart_list(request):
    # 部门列表
    queryset = models.Department.objects.all()
    return render(request, 'depart_list.html',{'queryset':queryset})

  • templates/depart_list.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.css' %}">
  <style>
    /* 去除导航条的圆角 */
    .navbar {
      border-radius: 0;
    }
  </style>
</head>

<body>
  <nav class="navbar navbar-default">
    <div class="container">
      <!-- Brand and toggle get grouped for better mobile display -->
      <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="#">部门管理</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="#">
          <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
          新建部门
        </a>
      </div>

      <div class="bs-example" data-example-id="table-within-panel">
        <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">编辑 </a>
                    <a class="btn btn-danger btn-xs">删除 </a>
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <script src="{% static 'js/jquery.slim.min.js' %}"></script>
  <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>

</body>
</html>

新建部门

  • urls.py
urlpatterns = [
    path('depart/list/',views.depart_list),
    path('depart/add/',views.depart_add),
]

  • views.py
def depart_add(request):
    # 添加页面
    if request.method == "GET":
        return render(request, 'depart_add.html')
    title = request.POST.get("title")
    models.Department.objects.create(title=title)
    return redirect('/depart/list/')
  • templates/depart_add.html
{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <style>
        /* 去除导航条的圆角 */
        .navbar {
            border-radius: 0;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-default">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <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="#">部门管理</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" name="title" placeholder="标题">
                        </div>
                        <button type="submit" class="btn btn-primary">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="{% static 'js/jquery.slim.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>

</body>

</html>

删除部门

  • urls.py
urlpatterns = [
    path('depart/list/',views.depart_list),
    path('depart/add/',views.depart_add),
    path('depart/delete/',views.depart_delete),
]

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

  • templates/depart_list.html
<tbody>
  {% for obj in queryset %}
  <tr>
    <th>{{obj.id}}</th>
    <td>{{obj.title}}</td>
    <td>
        <a class="btn btn-primary btn-xs">编辑 </a>
        <a class="btn btn-danger btn-xs" href="/depart/delete/?nid={{obj.id}}">删除 </a>
    </td>
  </tr>
  {% endfor %}
</tbody>

编辑部门

  • urls.py
urlpatterns = [
    path('depart/list/',views.depart_list),
    path('depart/add/',views.depart_add),
    path('depart/delete/',views.depart_delete),
    # <int:nid>正则表达式
    path('depart/<int:nid>/edit/',views.depart_edit),
]
  • views.py
def depart_edit(request,nid):
    # 修改部门
    if request.method == "GET":
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html',{'row_object':row_object})
    title = request.POST.get("title")
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')


  • templates/depart_list.html
<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>
  • templates/depart_edit.html
{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <style>
        /* 去除导航条的圆角 */
        .navbar {
            border-radius: 0;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-default">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <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="#">部门管理</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" name="title" placeholder="标题" value="{{row_object.title}}">
                        </div>
                        <button type="submit" class="btn btn-primary">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="{% static 'js/jquery.slim.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>

</body>

</html>

模版的继承

  • 在模版页layout.html中添加{% block 模块名 %}{% endblock %}
  • 其他页面可以使用{% extends 'layout.html' %}继承layout.html
  • 并在{% block 模块名 %}{% endblock %}内部编写独有内容
  • 模板页面:base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
  • 继承模板:extend.html
{% extends 'base.html' %}
{% block content %}
    <h1>hello world</h1>
{% endblock %}

使用模板更新部门管理页面

  • templates/layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <style>
        /* 去除导航条的圆角 */
        .navbar {
            border-radius: 0;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-default">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <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>
        {% block content %}{% endblock %}
    </div>

    <script src="{% static 'js/jquery.slim.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>

</body>

</html>
  • templates/depart_list.html
{% extends 'layout.html' %}
{% block content %}

<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="bs-example" data-example-id="table-within-panel">
    <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>

{% endblock %}
  • templates/depart_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" name="title" placeholder="标题">
                </div>
                <button type="submit" class="btn btn-primary">提交</button>
            </form>
        </div>
    </div>
</div>

{% endblock %}
  • templates/depart_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">
                {% csrf_token %}
                <div class="form-group">
                    <label>标题</label>
                    <input type="text" class="form-control" name="title" placeholder="标题" value="{{row_object.title}}">
                </div>
                <button type="submit" class="btn btn-primary">提交</button>
            </form>
        </div>
    </div>
</div>

{% endblock %}

用户管理

手动插入数据

insert into app01_userinfo(name,password,age,account,create_time,gender,depart_id) values("张三","123",23,100.66,"2010-11-11",1,2),("李四","1234",23,1333.66,"2012-11-11",2,7);

用户列表

  • urls.py
urlpatterns = [
    # 部门管理
    # ...
    # 用户管理
    path('depart/list/', views.depart_list),

]

  • views.py
def user_list(request):
    queryset = models.UserInfo.objects.all()
    return render(request, 'user_list.html', {'queryset': queryset})
  • templates/layout.html
<ul class="nav navbar-nav">
    <li><a href="/depart/list/">部门管理</a></li>
    <li><a href="/user/list/">用户管理</a></li>
</ul>
  • 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="bs-example" data-example-id="table-within-panel">
    <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.account}}</td>
            <td>{{obj.create_time|date:"Y-m-d"}}</td>
            <td>{{obj.get_gender_display}}</td>
            <td>{{obj.depart.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>

{% endblock %}

新建用户

原始方法思路

  • urls.py
urlpatterns = [
    # 用户管理
    path('user/list/', views.user_list),
    path('user/add/', views.user_add),
]

  • views.py
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)
    name = request.POST.get("name")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender_id = request.POST.get("gd")
    depart_id = request.POST.get("dp")
    models.UserInfo.objects.create(name=name, password=pwd, age=age,
                                     account=account, create_time=ctime, gender=gender_id, depart_id=depart_id)
    return redirect('/user/list/')
  • templates/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" name="name" placeholder="姓名">
                </div>
                <div class="form-group">
                    <label>密码</label>
                    <input type="text" class="form-control" name="pwd" placeholder="密码">
                </div>
                <div class="form-group">
                    <label>年龄</label>
                    <input type="text" class="form-control" name="age" placeholder="年龄">
                </div>
                <div class="form-group">
                    <label>余额</label>
                    <input type="text" class="form-control" name="ac" placeholder="余额">
                </div>
                <div class="form-group">
                    <label>入职时间</label>
                    <input type="text" class="form-control" name="ctime" placeholder="入职时间">
                </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 depart_list %}
                            <option value="{{item.id}}">{{item.title}}</option>
                        {% endfor %}
                    </select>
                </div>


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

{% endblock %}

原始方法问题:

  • 用户提交数据没有校验
  • 页面上应该有错误提示
  • 页面上每个字段都要重新写一遍
  • 关联的数据,手动获取并展示,费劲

使用Django组件

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

初识Form

  • views.py
class MyForm(Form):
    user = forms.CharField(widget=forms.Input)
    pwd = forms.CharField(widget=forms.Input)
    email = forms.CharField(widget=forms.Input)

def user_add(request):
    form=MyForm()
    return render(request, 'user_add.html', {"form":form})

  • templates/user_add.html
<form method="post">
    {% csrf_token %}
    {% for field in form %}
        {{field}}
    {% endfor %}

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

ModelForm【推荐】

  • models.py
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.DateField(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)

  • views.py
class MyForm(ModelForm):
    xx=form.CharField("...")
    class Meta:
        model=UserInfo
        fields=["name","password","age","xx"]
        
def user_add(request):
    form=MyForm()
    return render(request, 'user_add.html', {"form":form})

  • templates/user_add.html
<form method="post">
    {% csrf_token %}
    {% for field in form %}
        {{field}}
    {% endfor %}

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

新建用户【ModelForm】

  • models.py
from django.db import models


class Department(models.Model):
    # 部门表
    title = models.CharField(verbose_name="标题", max_length=32)
    def __str__(self):
        return self.title
    

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.DateField(verbose_name="入职时间")
    # #部门被删除,员工置空
    # depart = models.ForeignKey(
    #     to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)
    # 部门被删除,员工级联删除
    depart = models.ForeignKey(verbose_name="部门",
        to="Department", to_field="id", on_delete=models.CASCADE)
    gender_choices=(
        (1,"男"),
        (2,"女")
    )
    # 只能选择1、2
    gender=models.SmallIntegerField(verbose_name="性别",choices=gender_choices)


  • views.py
class UserModelForm(forms.ModelForm):
    #验证规则
    name = forms.CharField(min_length=3, label="用户名")
    
    class Meta:
        model=models.UserInfo
        fields=["name","password","age","create_time","gender","depart"]
        widgets={
            "password":forms.PasswordInput(attrs={"class":"form-control"})
        }

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        # 给所有字段的input框加上class:"form-control"
        for name,field in self.fields.items():
            if name=="password":
                continue
            field.widget.attrs = {"class":"form-control","placeholder":field.label}

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")
    else:
        #校验失败,form中包含错误信息和用户之前提交的数据
        return render(request,'user_model_form_add.html',{"form":form})

  • templates/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" 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 %}
  • settings.py
LANGUAGE_CODE = 'zh-hans'
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-09-04 01:07:23  更:2022-09-04 01:10:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/26 13:34:51-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计