You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django实现任务状态无刷新动态过滤方案求助

动态筛选任务列表解决方案

问题根源

现有代码的核心问题是:下拉选项传递的是状态码(如"I"、"C"),但JS筛选时匹配的是页面显示的状态文本(如"Pending"、"Completed"),两者不对应,导致筛选逻辑完全失效。


方案一:纯客户端过滤(无需修改后端)

1. 调整HTML模板,为状态单元格添加状态码标识

在任务状态的<td>标签中增加data-status属性,存储任务的原始状态码:

<td class="table-data" data-status="{{ task.status }}">
    <h3 class="label-tag">
        {% if task.status == 'I' %}
            Pending
        {% elif task.status == 'C' %}
            Completed
        {% elif task.status == 'R' %}
            Submitted for Review
        {% else %}
            Unknown
        {% endif %}
    </h3>
</td>

2. 修正JS筛选逻辑,匹配状态码而非文本

function myFunction(filter) {
  const table = document.querySelector(".main-table");
  const trList = table.querySelectorAll("tbody tr"); // 只筛选数据行,排除表头
  
  filter = filter.toUpperCase();
  // 处理"Show all"和默认选项的情况
  if (filter === "SHOW ALL" || filter === "#") {
    trList.forEach(tr => tr.style.display = "");
    return;
  }

  trList.forEach(tr => {
    const statusTd = tr.querySelector("td[data-status]");
    if (statusTd) {
      const taskStatus = statusTd.getAttribute("data-status").toUpperCase();
      // 直接匹配状态码
      tr.style.display = taskStatus === filter ? "" : "none";
    }
  });
}

function getOption() {
  const selectElement = document.querySelector('#select1');
  myFunction(selectElement.value);
}

方案二:后端API+AJAX(适合大数据量场景)

1. 添加Django筛选API视图

在views.py中新增返回筛选后任务HTML片段的视图:

from django.http import JsonResponse
from django.template.loader import render_to_string

def filter_tasks(request, project_id):
    status = request.GET.get('status', '')
    project_instance = project.objects.get(projectID=project_id)
    task_instance = Task.objects.filter(projectID=project_instance)
    
    # 根据状态筛选任务
    if status and status not in ['#', 'Show all']:
        task_instance = task_instance.filter(status=status)
    
    # 渲染任务列表片段
    html = render_to_string('manager/includes/task_list_rows.html', {
        'task_instance': task_instance,
        'project_instance': project_instance
    })
    return JsonResponse({'html': html})

2. 拆分任务列表为独立模板片段

新建manager/includes/task_list_rows.html,存放表格tbody内容:

{% for task in task_instance %}
<tr class="table-row">
    <td class="table-data">{{ task.taskTitle }}</td>
    <td class="table-data">
        <h3 class="label-tag">
            {% if task.status == 'I' %}
                Pending
            {% elif task.status == 'C' %}
                Completed
            {% elif task.status == 'R' %}
                Submitted for Review
            {% else %}
                Unknown
            {% endif %}
        </h3>
    </td>
    <td class="table-data">
        <a href="{% url 'view-tasks' project_id=project_instance.projectID %}">
            <button class="button-tag btns">View</button>
        </a>
    </td>
</tr>
{% empty %}
<tr class="table-row">
    <td class="table-data" colspan="3">No tasks to show</td>
</tr>
{% endfor %}

3. 修改主模板引入片段

将原表格的tbody替换为带ID的容器,引入片段:

<tbody id="task-table-body">
    {% include 'manager/includes/task_list_rows.html' %}
</tbody>

4. 替换JS为AJAX请求

function getOption() {
  const selectElement = document.querySelector('#select1');
  const status = selectElement.value;
  const projectId = "{{ project_instance.projectID }}";
  
  // 发送筛选请求
  fetch(`/filter-tasks/${projectId}/?status=${encodeURIComponent(status)}`)
    .then(res => res.json())
    .then(data => {
        document.querySelector('#task-table-body').innerHTML = data.html;
    })
    .catch(err => console.error('筛选失败:', err));
}

5. 添加URL路由

在urls.py中新增API路由:

path('filter-tasks/<int:project_id>/', views.filter_tasks, name='filter-tasks'),

内容的提问来源于stack exchange,提问作者Shlok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:08:12