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

在Django中如何将列表项的值传递给视图方法实现数据过滤?

实现方案

你只需要修改3处代码即可完成需求:

1. 修改index.html导航链接,携带subject参数

把每个<a>标签的href加上GET参数,传递当前点击的科目名称:

<ul class="submenu dropdown-menu">
  <li><a class="dropdown-item" href="{% url 'pdfNotes'%}?subject=MIS">MIS</a></li>
  <li><a class="dropdown-item" href="{% url 'pdfNotes'%}?subject=MA">MA</a></li>
  <li><a class="dropdown-item" href="{% url 'pdfNotes'%}?subject=UXD">UXD</a></li>
  <li><a class="dropdown-item" href="{% url 'pdfNotes'%}?subject=OSS">OSS</a></li>
</ul>

原来的name属性无需保留,直接通过URL的GET参数传递值即可

2. 修改views.py的筛选逻辑

修正参数获取和筛选逻辑,避免参数不存在时抛出异常,同时适配所有科目:

def pdfNotes(request):
    # 先获取URL传递的subject参数,不存在则为None
    subject = request.GET.get('subject', None)
    if subject:
        # 有科目参数就筛选对应科目的笔记
        pdfNotes_file = PDF_Notes.objects.filter(subject=subject)
    else:
        # 没有参数就返回全部笔记
        pdfNotes_file = PDF_Notes.objects.all()
    n = len(pdfNotes_file)
    params = {'pdfnote': pdfNotes_file, 'total_items': n}
    return render(request, 'pdfNotes.html', params)

注意不要用request.GET['xxx']的写法,参数不存在时会直接抛出KeyError报错,用get方法更安全

3. 修正pdfNotes.html的模板错误

你的模板表头和单元格数量不匹配,而且部分变量没有传值,修正如下:

{% if pdfnote %}
<table>
    <tr>
        <th>#</th>
        <th>课程</th>
        <th>学期</th>
        <th>年份</th>
        <th>NAME</th>
        <th>DOWNLOAD FILE</th>
    </tr>
    {% for item in pdfnote %}
    <tr>
        <td class="id">{{ forloop.counter }}</td>
        <td class="course">{{ item.course }}</td>
        <td class="semester">{{ item.semester }}</td>
        <td class="year">{{ item.year }}</td>
        <td class="name">{{ item.name }}</td>
        <td class="downloadBtn">
            <a href="{{ item.file.url }}" class="btn-outline-success" download>DOWNLOAD</a>
        </td>
    </tr>
    {% endfor %}
</table>
{% endif %}

注意HTML中id属性不能重复,这里统一改为class;同时删除了无用的with标签,直接调用item的属性取值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:48:01