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)输入错误信息,即非部门信息,进行搜索

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

相关推荐
研究点啥好呢1 分钟前
Github热榜项目推荐 | Fireworks Tech Graph:告别手动绘图时代
python·开源·github·claude·skills
ycjunhua3 分钟前
终极入门:uv —— 超快 Python 包 / 环境管理工具(Windows 完整版)
windows·python·uv
2401_883600253 分钟前
SQL视图名称冲突如何避免_建立规范化的命名空间与管理
jvm·数据库·python
de_wizard4 分钟前
Spring Boot 整合 Apollo 配置中心实战
java·spring boot·后端
用户6757049885024 分钟前
AI开发实战1、手摸手教你一行代码不写,全程AI写个小程序——前端布局
后端·aigc·ai编程
JAVA学习通5 分钟前
AI Agent 工具调用机制深度解析与 Spring Boot 工程集成实战(2026版)
java·人工智能·spring boot·python·spring
ooseabiscuit5 分钟前
Spring报错解决一览
java·后端·spring
亿牛云爬虫专家5 分钟前
解决 Python 爬虫代理 407 错误:基于 urllib3 更新与爬虫代理的实战指南-2
爬虫·python·爬虫代理·authentication·urllib3·407·base64 编码
m0_640309306 分钟前
CSS中如何让浮动元素撑开父容器_深度解析清除浮动
jvm·数据库·python
2301_816660216 分钟前
Golang bufio怎么读取用户输入_Golang标准输入读取教程【详解】
jvm·数据库·python