• Python Web开发记录 Day11:Django part5 管理员管理


    名人说:莫道桑榆晚,为霞尚满天。——刘禹锡(刘梦得,诗豪)
    创作者:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊)

    1、创建管理员表

    image-20240314155955534

    在models.py中添加Admin类。

    class Admin(models.Model):
        """管理员"""
        username = models.CharField(verbose_name="用户名",max_length=32)
        password = models.CharField(verbose_name="密码",max_length=64)
    
    • 1
    • 2
    • 3
    • 4

    之后终端运行数据库生成转移

    python manage.py makemigrations
    python manage.py migrate
    
    • 1
    • 2

    image-20240314160511825

    登录mysql,然后查看数据库中的表,可以发现admin数据表已经创建。

    image-20240314160558770

    layout.html加入管理员账户。

    <li><a href="/admin/list">管理员账户a>li>
    
    • 1

    image-20240314160831789

    往admin表中插入数据

    insert into api_admin(username, password) values("张三", "123456");
    insert into api_admin(username, password) values("李四", "123456");
    insert into api_admin(username, password) values("王五", "123456");
    
    mysql> insert into api_admin(username, password) values("王五", "123456");
    Query OK, 1 row affected (0.05 sec)
    
    mysql> select * from api_admin;
    +----+----------+----------+
    | id | username | password |
    +----+----------+----------+
    |  1 | 张三     | 123456   |
    |  2 | 李四     | 123456   |
    |  3 | 王五     | 123456   |
    +----+----------+----------+
    3 rows in set (0.01 sec)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    2、管理员列表

    这一部分仍然和咱们之前所实践过的用户管理、靓号管理等相似。

    1.在urls.py中添加用户列表的路径admin/list/,并告诉该路径指向的视图view.admin_list

    urls.py

    from django.urls import path
    from api.views import depart,user,pretty
    
    urlpatterns = [
        # 部门管理
        path("depart/list/", depart.depart_list),
        path("depart/add/", depart.depart_add),
        path("depart/delete/", depart.depart_delete),
        path("depart//edit/", depart.depart_edit),
    
        # 用户管理
        path("user/list/", user.user_list),
        path("user/add/", user.user_add),
        path("user/model/form/add/", user.user_model_form_add),
        path('user//edit/', user.user_edit),
        path("user//delete/", user.user_delete),
    
        # 靓号管理
        path("pretty/list/", pretty.pretty_list),
        path("pretty/add/", pretty.pretty_add),
        path("pretty//edit/", pretty.pretty_edit),
        path("pretty//delete/", pretty.pretty_delete),
    
        # 管理员管理
        path('admin/list/', admin.admin_list),
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    2.在views文件夹下新建admin.py,在admin.py中写出对应的函数,发出请求,并返回响应admin_list.html

    admin.py

    from django.shortcuts import render, redirect
    from api.models import Admin
    from api.utils.pagination import Pagination
    from api.utils.form import BootStrapModelForm
    from api.utils.form import AdminModelForm, AdminEditModelForm, AdminResetModelForm
    
    
    def admin_list(request):
        """管理员列表"""
    
        data_dict = {}
        # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
        search_data = request.GET.get('query', "")
        if search_data:
            data_dict["username__contains"] = search_data
    
        queryset = Admin.objects.filter(**data_dict).order_by("id")
    
        # queryset = Admin.objects.all()
        page_object = Pagination(request, queryset, page_size=2)
        page_queryset = page_object.page_queryset
        page_object.html()
        page_string = page_object.page_string
    
        context = {
            "page_queryset": page_queryset,
            "page_string": page_string,
            "search_data": search_data,
        }
        return render(request, 'admin_list.html', context)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    3.创建templates目录下模版html文件admin_list.html,以此定义部门列表的网页结构和布局。

    修改之前的layout.html模板,增加管理员板块。

    {% load static %}
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        
        <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}">
        <link rel="stylesheet" href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.css' %}">
    
        
        <link rel="stylesheet" type="text/css"
              href="{% static 'plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css' %}">
        <style>
            .navbar {
                border-radius: 0;
            }
        style>
        {% block css %}
    
        {% endblock %}
    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 navigationspan>
                    <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="/admin/list">管理员账户a>li>
                    <li><a href="/depart/list">部门管理a>li>
                    <li><a href="/user/list">用户管理a>li>
                    <li><a href="/pretty/list">靓号管理a>li>
    
                    <li class="active"><a href="#">Link <span class="sr-only">(current)span>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><a href="#">Something else herea>li>
                            <li role="separator" class="divider">li>
                            <li><a href="#">注销a>li>
                        ul>
                    li>
    
                ul>
            div>
        div>
    nav>
    
    <div>
        <div class="container">
            {% block content %}{% endblock %}
        div>
    div>
    
    {% block js %}
        <script src="{% static 'js/jquery.min.js' %}">script>
        
        <script src="{% static 'plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js' %}">script>
        <script src="{% static 'plugins/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js' %}">script>
        <script type="text/javascript">
        $(function () {
            //当容器加载完成,对容器调用工具函数
            $("#dt").datetimepicker({
                language: 'zh-CN', //语言
                format: 'yyyy-mm-dd',//日期的格式
                minView: 'month', //可以选择的最小视图
                initialDate: new Date(),//初始化显示的日期
                autoclose: true,//设置选择完日期或者时间之后,日否自动关闭日历
                todayBtn: true,//设置自动显示为今天
                clearBtn: false//设置是否清空按钮,默认为false
            });
        });
        script>
    {% endblock %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91

    admin_list.html

    {% extends 'layout.html' %}
    
    {% block content %}
    <div class="container">
    
        <div>
            <div style="margin-bottom: 10px; ">
                <a class="btn btn-primary" href="/admin/add/" target="_blank">新建管理员a>
    
                <div style="float: right; width: 300px;">
                    <form method="get">
                        <div class="input-group">
                            <input type="text" name="query" class="form-control" placeholder="Search for..."
                                value="{{ search_data }}">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="submit">
                                    <span class="glyphicon glyphicon-search" aria-hidden="true">span>
                                button>
                            span>
                        div>
                    form>
                div>
            div>
        div>
    
        <div>
            <div class="panel panel-default">
                
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="margin-right: 5px;">span>
                    <span>管理员列表span>
                div>
    
                
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>IDth>
                            <th>姓名th>
                            <th>密码th>
                            <th>重置密码th>
                            <th>操作th>
                        tr>
                    thead>
                    <tbody>
                        {% for obj in page_queryset %}
                        <tr>
                            <th>{{ obj.id }}th>
                            <td>{{ obj.username }}td>
                            <td>{{ obj.password }}td>
                            <td>
                                <a href="/admin/{{ obj.id }}/reset/">重置密码a>
                            td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/admin/{{ obj.id }}/edit/">编辑a>
                                <a class="btn btn-danger btn-xs" href="/admin/{{ obj.id }}/delete/">删除a>
                            td>
                        tr>
                        {% endfor %}
                    tbody>
                table>
            div>
        div>
    
        <ul class="pagination">
            {{ page_string }}
        ul>
        <br>
    
        <form method="get">
            <div style="display:inline-block; width: 150px;">
                <div class="input-group">
                    <span> <input type="text" class="form-control" placeholder="请输入页码" name="page">span>
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit">跳转button>
                    span>
                div>
            div>
        form>
    div>
    
    {% endblock %}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83

    效果:

    image-20240315150929475

    3、添加管理员

    同样地我们来实现添加管理员。

    ①添加管理员

    1.在urls.py中添加用户列表的路径admin/add/,并告诉该路径指向的视图view.admin_add

    urls.py

     from django.urls import path
     from api.views import depart,user,pretty
     
     urlpatterns = [
        # 部门管理
        path("depart/list/", depart.depart_list),
        path("depart/add/", depart.depart_add),
        path("depart/delete/", depart.depart_delete),
        path("depart//edit/", depart.depart_edit),
    
        # 用户管理
        path("user/list/", user.user_list),
        path("user/add/", user.user_add),
        path("user/model/form/add/", user.user_model_form_add),
        path('user//edit/', user.user_edit),
        path("user//delete/", user.user_delete),
    
        # 靓号管理
        path("pretty/list/", pretty.pretty_list),
        path("pretty/add/", pretty.pretty_add),
        path("pretty//edit/", pretty.pretty_edit),
        path("pretty//delete/", pretty.pretty_delete),
    
        # 管理员管理
        path('admin/list/', admin.admin_list),
        path('admin/add/', admin.admin_add),
     ]
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    2.修改admin.py,添加以下函数,发出请求,并返回响应admin_add.html

    admin.py

    def admin_add(request):
        """添加管理员"""
    
        title = "新建管理员"
    
        if request.method == "GET":
            form = AdminModelForm()
            return render(request, "admin_add.html", {"form": form, "title": title})
    
        # 如果是POST请求
        form = AdminModelForm(data=request.POST)
    
        context = {
            "form": form,
            "title": title,
        }
    
        if form.is_valid():
            form.save()
            return redirect("/admin/list")
    
        return render(request, "admin_add.html", context)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    3.创建templates目录下模版html文件admin_add.html,以此实现用户信息的新增。

    admin_add.html

    {% extends 'layout.html' %}
    
    
    {% block content %}
    
        <div class="container">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"> {{ 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 %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    效果:

    image-20240315151502618

    ②密码一致检验

    在form.py中添加管理员类,并增加钩子函数用作密码一致检验:

    class AdminModelForm(BootStrapModelForm):
        confirm_password = forms.CharField(
            label="确认密码",
            widget=forms.PasswordInput,
        )
    
        class Meta:
            model = Admin
            fields = ["username", "password", "confirm_password"]
            widgets = {
                "password": forms.PasswordInput
            }
    
        # 钩子函数
        def clean_confirm_password(self):
            pwd = self.cleaned_data.get("password")
            confirm = self.cleaned_data.get("confirm_password")
            if confirm != pwd:
                raise ValidationError("密码不一致!")
            return confirm
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    效果:

    在这里插入图片描述

    密码一致检验的问题是解决了,但密码这样存储进数据库,很不安全。因此我们需要对其进行加密后,再进行保存,以确保数据安全。

    ③密码加密(采用md5加密)

    在实现之前,我们首先先了解一下什么是md5加密:

    MD5加密是一种广泛使用的加密方式,而且在Python中进行MD5加密非常简单,可以使用内置的hashlib模块来完成这个任务。以下是一个示例代码,展示了如何将字符串进行MD5加密:

    import hashlib
    
    # 要加密的字符串
    text = "你要加密的字符串"
    
    # 使用MD5加密
    md5 = hashlib.md5(text.encode()).hexdigest()
    
    print(md5)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    这段代码首先导入了hashlib模块,然后定义了一个要加密的字符串text。使用hashlib.md5()方法对字符串进行加密,由于hashlib.md5()需要的是字节类型的参数,所以我们使用encode()方法将字符串转换成字节。hexdigest()方法将加密后的字节结果转换为十六进制的字符串形式。

    但需要注意的是,由于其安全性已经不被完全信任,对于需要高安全性的应用场景,建议使用更安全的加密算法,如SHA-256等。

    在上面的基础上,在utils文件夹下新建encrypt.py文件

    # hashlib包用于提供常见的哈希算法。
    # hashlib支持多种算法,如MD5、SHA1、SHA224、SHA256、SHA384和SHA512等。
    import hashlib
    from django.conf import settings
    
    def md5(data_string):
        obj = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))
        obj.update(data_string.encode('utf-8'))
        return obj.hexdigest()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    之后在form.py中修改管理员类:

    class AdminModelForm(BootStrapModelForm):
        confirm_password = forms.CharField(
            label="确认密码",
            # 点击提交后,密码和密码确认框中的数据清空了,这也是个问题,加上render_value=True之后问题解决
            widget=forms.PasswordInput(render_value=True)
        )
    
        class Meta:
            model = Admin
            fields = ["username", "password", "confirm_password"]
            widgets = {
                "password": forms.PasswordInput(render_value=True)
            }
    
        def clean_password(self):
            pwd = self.cleaned_data.get("password")
            md5_pwd = md5(pwd)
    
            # 去数据库校验当前密码和新输入的密码是否一致
            exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
            if exists:
                raise ValidationError("不能与以前的密码相同")
    
            return md5_pwd
    
        def clean_confirm_password(self):
            pwd = self.cleaned_data.get("password")
            confirm = md5(self.cleaned_data.get("confirm_password"))
            if confirm != pwd:
                raise ValidationError("密码不一致")
            # 返回什么,此字段以后保存到数据库就是什么。
            return confirm
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    修改之后,原来的密码123456就被加密成了如下格式:

    效果如下:

    image-20240315153612442

    4、编辑管理员

    实现完列表和添加功能后,我们来实现编辑功能,方便修改信息。

    1.在urls.py中添加用户列表的路径admin//edit/,并告诉该路径指向的视图view.admin_edit

    urls.py

     from django.urls import path
     from api.views import depart,user,pretty
     
     urlpatterns = [
        # 部门管理
        path("depart/list/", depart.depart_list),
        path("depart/add/", depart.depart_add),
        path("depart/delete/", depart.depart_delete),
        path("depart//edit/", depart.depart_edit),
    
        # 用户管理
        path("user/list/", user.user_list),
        path("user/add/", user.user_add),
        path("user/model/form/add/", user.user_model_form_add),
        path('user//edit/', user.user_edit),
        path("user//delete/", user.user_delete),
    
        # 靓号管理
        path("pretty/list/", pretty.pretty_list),
        path("pretty/add/", pretty.pretty_add),
        path("pretty//edit/", pretty.pretty_edit),
        path("pretty//delete/", pretty.pretty_delete),
    
        # 管理员管理
        path('admin/list/', admin.admin_list),
        path('admin/add/', admin.admin_add),
        path('admin//edit/',admin.admin_edit),
     ]
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    2.在form.py中添加管理员编辑类,在admin.py中写出对应的函数,发出请求,并返回响应admin_add.html

    在form.py中添加管理员编辑类:

    class AdminEditModelForm(BootStrapModelForm):
        class Meta:
            model = Admin
            fields = ["username"]
    
    • 1
    • 2
    • 3
    • 4

    admin.py

    def admin_edit(request, nid):
        # 判断nid是否存在
        row_object = Admin.objects.filter(id=nid).first()
        if not row_object:
            return render(request, "error.html", {"msg": "数据不存在!"})
    
        """编辑管理员"""
    
        title = "编辑管理员"
    
        if request.method == "GET":
            form = AdminEditModelForm(instance=row_object)
            return render(request, "admin_add.html", {"form": form, "title": title})
    
        form = AdminEditModelForm(data=request.POST, instance=row_object)
        if form.is_valid():
            form.save()
            return redirect('/admin/list')
    
        return render(request, "admin_add.html", {"form": form, "title": title})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3.修改admin_add.html

    修改admin_list.html中的,设置编辑功能href=“URL路径”。

    image-20240315155013158

    修改admin_add.html

    {% extends 'layout.html' %}
    
    
    {% block content %}
    
        <div class="container">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"> {{ 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 %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    效果:

    121

    5、删除管理员

    与上述步骤相仿,我们继续来实现删除管理员,删除管理员的基础是建立在管理员列表的实现和新增管理员的功能之上的。

    1.在urls.py中添加用户列表的路径admin//delete/,并告诉该路径指向的视图view.admin_delete

    urls.py

    from django.urls import path
    from api.views import depart, user, pretty, admin
    
    urlpatterns = [
    
        # 部门管理
        path("depart/list/", depart.depart_list),
        path("depart/add/", depart.depart_add),
        path("depart/delete/", depart.depart_delete),
        path("depart//edit/", depart.depart_edit),
    
        # 用户管理
        path("user/list/", user.user_list),
        path("user/add/", user.user_add),
        path("user/model/form/add/", user.user_model_form_add),
        path('user//edit/', user.user_edit),
        path("user//delete/", user.user_delete),
    
        # 靓号管理
        path("pretty/list/", pretty.pretty_list),
        path("pretty/add/", pretty.pretty_add),
        path("pretty//edit/", pretty.pretty_edit),
        path("pretty//delete/", pretty.pretty_delete),
    
        # 管理员管理
        path('admin/list/', admin.admin_list),
        path('admin/add/', admin.admin_add),
        path('admin//edit/',admin.admin_edit),
        path('admin//delete/', admin.admin_delete),
        path('admin//reset/',admin.admin_reset),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    2.在admin.py中写出对应的函数,发出请求,并返回响应admin_list.html

    admin.py

    def admin_delete(request, nid):
        """删除管理员"""
        Admin.objects.filter(id=nid).delete()
        return redirect("/admin/list/")
    
    • 1
    • 2
    • 3
    • 4

    3.操作templates目录下模版html文件admin_list.html,以此实现用户信息的删除。

    admin_list.html

    {% extends 'layout.html' %}
    
    {% block content %}
    <div class="container">
    
        <div>
            <div style="margin-bottom: 10px; ">
                <a class="btn btn-primary" href="/admin/add/" target="_blank">新建管理员a>
    
                <div style="float: right; width: 300px;">
                    <form method="get">
                        <div class="input-group">
                            <input type="text" name="query" class="form-control" placeholder="Search for..."
                                value="{{ search_data }}">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="submit">
                                    <span class="glyphicon glyphicon-search" aria-hidden="true">span>
                                button>
                            span>
                        div>
                    form>
                div>
            div>
        div>
    
        <div>
            <div class="panel panel-default">
                
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="margin-right: 5px;">span>
                    <span>管理员列表span>
                div>
    
                
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>IDth>
                            <th>姓名th>
                            <th>密码th>
                            <th>重置密码th>
                            <th>操作th>
                        tr>
                    thead>
                    <tbody>
                        {% for obj in page_queryset %}
                        <tr>
                            <th>{{ obj.id }}th>
                            <td>{{ obj.username }}td>
                            <td>{{ obj.password }}td>
                            <td>
                                <a href="/admin/{{ obj.id }}/reset/">重置密码a>
                            td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/admin/{{ obj.id }}/edit/">编辑a>
                                <a class="btn btn-danger btn-xs" href="/admin/{{ obj.id }}/delete/">删除a>
                            td>
                        tr>
                        {% endfor %}
                    tbody>
                table>
            div>
        div>
    
        <ul class="pagination">
            {{ page_string }}
        ul>
        <br>
    
        <form method="get">
            <div style="display:inline-block; width: 150px;">
                <div class="input-group">
                    <span> <input type="text" class="form-control" placeholder="请输入页码" name="page">span>
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit">跳转button>
                    span>
                div>
            div>
        form>
    div>
    
    {% endblock %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    效果:

    122

    6、重置密码(重置成新密码)

    除了上述常见功能外,考虑到忘记密码需要重置密码的需求,在管理员模块中增加此功能,实现方法与上述几个功能相似,实现思路关键在于怎么理解上面的编辑功能,将编辑功能中修改密码那一块提取出来,并在数据库中实时响应即可。

    1.在urls.py中添加用户列表的路径admin//reset/,并告诉该路径指向的视图view.admin_reset

    urls.py

    from django.urls import path
    from api.views import depart, user, pretty, admin
    
    urlpatterns = [
    
        # 部门管理
        path("depart/list/", depart.depart_list),
        path("depart/add/", depart.depart_add),
        path("depart/delete/", depart.depart_delete),
        path("depart//edit/", depart.depart_edit),
    
        # 用户管理
        path("user/list/", user.user_list),
        path("user/add/", user.user_add),
        path("user/model/form/add/", user.user_model_form_add),
        path('user//edit/', user.user_edit),
        path("user//delete/", user.user_delete),
    
        # 靓号管理
        path("pretty/list/", pretty.pretty_list),
        path("pretty/add/", pretty.pretty_add),
        path("pretty//edit/", pretty.pretty_edit),
        path("pretty//delete/", pretty.pretty_delete),
    
        # 管理员管理
        path('admin/list/', admin.admin_list),
        path('admin/add/', admin.admin_add),
        path('admin//edit/',admin.admin_edit),
        path('admin//delete/', admin.admin_delete),
        path('admin//reset/',admin.admin_reset),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    2.在admin.py中写出对应的函数,发出请求,并返回响应admin_list.html

    在form.py中新增重置模块:

    class AdminResetModelForm(BootStrapModelForm):
        confirm_password = forms.CharField(
            label="确认密码",
            widget=forms.PasswordInput(render_value=True),
        )
    
        class Meta:
            model = Admin
            fields = ["password", "confirm_password"]
            widgets = {
                "password": forms.PasswordInput(render_value=True)
            }
    
        # clean_字段名
        def clean_password(self):
            pwd = self.cleaned_data.get("password")
    
            # 校验当前数据库中的密码与用户输入的新密码是否一致
            exists = Admin.objects.filter(id=self.instance.pk, password=md5(pwd))
            if exists:
                raise ValidationError("密码不能与当前密码一致!")
    
            # return什么.password字段保存什么
            return md5(pwd)
    
        # 钩子函数
        def clean_confirm_password(self):
            pwd = self.cleaned_data.get("password")
            confirm = self.cleaned_data.get("confirm_password")
            if md5(confirm) != pwd:
                raise ValidationError("密码不一致!")
    
            # return返回什么,字段 confirm_password 保存至数据库的值就是什么
            return md5(confirm)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    views.py

    def admin_reset(request, nid):
        """重置管理员密码"""
    
        # 判断nid是否存在
        """
        在Admin表中查找id等于nid的第一条记录,并将这条记录赋值给row_object变量。如果没有找到符合条件的记录,row_object将会是None。
        """
        row_object = Admin.objects.filter(id=nid).first()
        if not row_object:
            return render(request, "error.html", {"msg": "数据不存在!"})
    
        title = "重置密码 - {}".format(row_object.username)
    
        if request.method == "GET":
            form = AdminResetModelForm(instance=row_object)
            return render(request, "admin_add.html", {"title": title, "form": form})
        form = AdminResetModelForm(data=request.POST, instance=row_object)
        if form.is_valid():
            form.save()
            return redirect("/admin/list/")
    
        return render(request, "admin_add.html", {"title": title, "form": form})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    3.操作templates目录下模版html文件admin_list.html,以此实现用户信息的删除。

    admin_list.html

    {% extends 'layout.html' %}
    
    {% block content %}
    <div class="container">
    
        <div>
            <div style="margin-bottom: 10px; ">
                <a class="btn btn-primary" href="/admin/add/" target="_blank">新建管理员a>
    
                <div style="float: right; width: 300px;">
                    <form method="get">
                        <div class="input-group">
                            <input type="text" name="query" class="form-control" placeholder="Search for..."
                                value="{{ search_data }}">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="submit">
                                    <span class="glyphicon glyphicon-search" aria-hidden="true">span>
                                button>
                            span>
                        div>
                    form>
                div>
            div>
        div>
    
        <div>
            <div class="panel panel-default">
                
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="margin-right: 5px;">span>
                    <span>管理员列表span>
                div>
    
                
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>IDth>
                            <th>姓名th>
                            <th>密码th>
                            <th>重置密码th>
                            <th>操作th>
                        tr>
                    thead>
                    <tbody>
                        {% for obj in page_queryset %}
                        <tr>
                            <th>{{ obj.id }}th>
                            <td>{{ obj.username }}td>
                            <td>{{ obj.password }}td>
                            <td>
                                <a href="/admin/{{ obj.id }}/reset/">重置密码a>
                            td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/admin/{{ obj.id }}/edit/">编辑a>
                                <a class="btn btn-danger btn-xs" href="/admin/{{ obj.id }}/delete/">删除a>
                            td>
                        tr>
                        {% endfor %}
                    tbody>
                table>
            div>
        div>
    
        <ul class="pagination">
            {{ page_string }}
        ul>
        <br>
    
        <form method="get">
            <div style="display:inline-block; width: 150px;">
                <div class="input-group">
                    <span> <input type="text" class="form-control" placeholder="请输入页码" name="page">span>
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit">跳转button>
                    span>
                div>
            div>
        form>
    div>
    
    {% endblock %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    效果:

    123

    整体效果:

    125

    在这篇博客之后,管理板块将暂时告一段落,下篇内容我们将继续一起实现账户板块,实现用户注册、登录、图片验证码等功能。

    很感谢你能看到这里,如有相关疑问,还请下方评论留言。
    Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊)
    希望本篇内容能对大家有所帮助,如果大家喜欢的话,请动动手点个赞和关注吧,非常感谢你们的支持!

  • 相关阅读:
    java基于springboot+vue的在线求助系统
    27. UE5 RPG同步面板属性(三)
    比较分析线程池中execute与submit方法的差异
    网络-华为、思科交换机配置TFTP自动备份、NTP时间同步、SYSLOG日志同步功能
    从一个例子认识Spring MVC数据绑定
    勒索病毒最新变种.Malloxx勒索病毒来袭,如何恢复受感染的数据?
    3D面部重建,或将拯救他的颜值...
    Python开发自定义Web框架
    【c++11】cpp实现模板函数的声明与定义分离
    外包干了5天,技术明显退步。。。。。
  • 原文地址:https://blog.csdn.net/qq_51646682/article/details/136744261