07 django管理系统 - 部门管理 - 搜索部门

在dept_list.html中,添加搜索框
html 复制代码
    <div class="container-fluid">
        <div style="margin-bottom: 10px" class="clearfix">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <a class="btn btn-primary" href="/dept/add/" role="button">添加部门</a>

                    <!--因为涉及到提交以及数据路径拼接,所以需要一个form表单,method为get-->
                    <div style="float: right">
                        <form class="form-inline" action="/dept/search/" method="get">
                            <!--添加搜索框-->
                            <!--name=q 非常的重要-->

                            <input type="text" class="form-control" name="q" placeholder="请输入要搜索的部门"
                                   aria-label="Recipient's username" aria-describedby="button-addon2">
                            <button class="btn btn-outline-secondary" type="submit" id="button-addon2">搜索
                            </button>

                        </form>
                    </div>
                </div>


                <div class="panel-body">
                    <div style="float: left">
                        <p>部门列表</p>
                    </div>
                    <!-- Table -->
                    <table class="table">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>name</th>
                            <th>head</th>
                            <th>phone</th>
                            <th>email</th>
                            <th>address</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for obj in queryset %}
                            <tr>
                                <td>{{ obj.id }}</td>
                                <td>{{ obj.name }}</td>
                                <td>{{ obj.head }}</td>
                                <td>{{ obj.phone }}</td>
                                <td>{{ obj.email }}</td>
                                <td>{{ obj.address }}</td>

                                <td>
                                    <a class="btn btn-success" href="/dept/{{ obj.id }}/edit_detail/"
                                       role="button">编辑部门</a>
                                    <a class="btn btn-danger" href="/dept/{{ obj.id }}/delete/" role="button">删除部门</a>
                                </td>
                            </tr>

                        {% endfor %}
                        </tbody>
                    </table>
                    {% if error %}
                        <div style="color: red;">
                            {{ error }}
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

效果如下:

通过action="/dept/search/",我们需要配置URL

python 复制代码
urlpatterns = [
    # 部门管理
    path("dept/list/", dept.dept_list),
    path("dept/add/", dept.dept_add),
    path("dept/<int:nid>/edit_detail/", dept.dept_editdetail),
    path("dept/<int:nid>/delete/", dept.dept_delete),
    path("dept/search/", dept.dept_search),

]

接着去定义函数dept_search()的业务逻辑

python 复制代码
def dept_search(request):
    """
    实现部门搜索功能的视图函数。

    此函数根据用户提交的搜索关键字,查询并返回匹配的部门列表。
    如果没有提供关键字,则返回所有部门的列表。

    参数:
    - request: HttpRequest对象,包含了请求的所有数据。

    返回:
    - 渲染后的'dept_list.html'模板,包含搜索结果或错误信息。
    """
 
    data_dict = {}  # 首先定义一个空的字典
    keyvalue = request.GET.get("q")  # 取到关键字
    print("keyvalue", keyvalue)
    if keyvalue:
        data_dict["name__contains"] = keyvalue
        print("data_dict", data_dict)
        res = models.Dept.objects.using("default").filter(**data_dict)
        print("res", res)

        if not res.exists():
            # 返回错误信息
            print("未找到匹配的部门,请输入正确的部门名称")
            return render(request, 'dept_list.html', {"error": "未找到匹配的部门,请输入正确的部门名称"})

        queryset = res.order_by("-id")
        print("queryset", queryset)
        return render(request, 'dept_list.html', {"queryset": queryset})

我们尝试搜索一下:

1)我搜索正确的部门,比如我搜2病区,注意看调试情况

我们可以看到访问的具体情况,看红框

2) 假设我搜索空的

报错了,我们可以尝试修改代码

因为q没有默认值,这种没传值的情况下,我们直接显示全部列

python 复制代码
"""搜索部门"""


def dept_search(request):
    """
    实现部门搜索功能的视图函数。

    此函数根据用户提交的搜索关键字,查询并返回匹配的部门列表。
    如果没有提供关键字,则返回所有部门的列表。

    参数:
    - request: HttpRequest对象,包含了请求的所有数据。

    返回:
    - 渲染后的'dept_list.html'模板,包含搜索结果或错误信息。
    """

    data_dict = {}  # 首先定义一个空的字典
    keyvalue = request.GET.get("q")  # 取到关键字
    print("keyvalue....", keyvalue)
    if keyvalue:
        data_dict["name__contains"] = keyvalue
        print("data_dict", data_dict)
        res = models.Dept.objects.using("default").filter(**data_dict)
        print("res", res)

        if not res.exists():
            # 返回错误信息
            print("未找到匹配的部门,请输入正确的部门名称")
            return render(request, 'dept_list.html', {"error": "未找到匹配的部门,请输入正确的部门名称"})

        queryset = res.order_by("-id")
        print("queryset", queryset)
        return render(request, 'dept_list.html', {"queryset": queryset})

    # 如果考虑的全面一点,如果q没被传值,则查询全部
    if keyvalue == "":
        res = models.Dept.objects.using("default").all()
        print("qis'',res is..", res)
        context = {
            'queryset': res
        }
        queryset = res.order_by("-id")
        print("queryset", queryset)
        return render(request, 'dept_list.html', {"queryset": queryset})

注意下调试的情况

可以看到输入为空的时候,也是可以查询到数据的

3)输入错误信息,即非部门信息,进行搜索

这样,搜索的功能,我们就完成了。

相关推荐
JaguarJack5 小时前
PHP 引用计数机制深度解析
后端·php·服务端
郝学胜-神的一滴7 小时前
Python 高级编程 026:内置数据结构之骈文纵论
开发语言·数据结构·python·程序人生·软件工程
DLYSB_14 小时前
存储运维实战:基于 Ceph Event 监听与 Python 适配器的分布式存储健康度物理声光响应架构
运维·ceph·python·报警灯
陈随易14 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
阿童木写作14 小时前
跨境图片翻译工具多合一,批量图片视频字幕翻译加智能抠图
人工智能·python·音视频·语音识别
阿童木写作16 小时前
Python实现Temu图片批量翻译自动化教程
运维·人工智能·python·自动化
就是一只白17 小时前
复制地理信息python版本
python
凌虚17 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
看浪的路人17 小时前
第1讲:Agent 到底是什么?和 Chatbot 有什么区别
python·ai
瓦学妹18 小时前
什么是网络索引?它是如何工作的?
大数据·网络·python·网络爬虫