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

在Django中通过Bootstrap Modal展示POST请求返回数据的问题

问题分析与修复方案

你遇到的核心问题有三个:视图查询逻辑错误、AJAX返回内容未更新到Modal、模板变量使用不当,以下是分步修复方案:


1. 修复Django视图查询逻辑

视图中直接用字符串匹配外键字段会失败,同时字段名拼写错误(VID应为vid),修改后的视图如下:

def vulInfo(request):
    # 外键字段需通过__关联模型主键,且利用唯一约束直接取单个结果
    vul_data = clientvul.objects.filter(
        client__client=request.POST['client'],
        vid_id=request.POST['vid']
    ).first()
    # 返回单独的Modal内容模板,而非整个页面
    return render(request, 'vul_modal_content.html', {'vuldata': vul_data})

2. 创建单独的Modal内容模板

新建vul_modal_content.html文件,仅包含Modal内部动态内容:

<div class="modal-content">
    {% if vuldata %}
        <div class="modal-header">
            <h5 class="modal-title">漏洞详情</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <p>路径: {{ vuldata.path }}</p>
            <p>漏洞ID: {{ vuldata.vid.vid }}</p>
            <p>CVSS评分: {{ vuldata.vid.cvsscore }}</p>
            <p>漏洞标题: {{ vuldata.vid.title }}</p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        </div>
    {% else %}
        <div class="modal-body">
            <p>未找到对应漏洞信息</p>
        </div>
    {% endif %}
</div>

3. 修改前端AJAX逻辑,更新Modal内容

原JS仅显示静态Modal,需将AJAX返回的动态内容替换到Modal容器中:

$(function () {
  $(".form-select").change(function (event) {
    let $vid = this.value;
    // 去除字符串首尾空白,避免匹配失败
    let $hostname = $(this).closest('tr').find('td.hostname').text().trim();
    // 取消选中状态
    for(var i = 0; i < this.options.length; i++){
          this.options[i].selected = false;
    }
    $.ajax({
        type: "POST",
        url: '/api/vulinfo',
        data: {
          'client': $hostname,
          'vid' : $vid,
          // 若JS在单独文件中,需通过页面隐藏域获取CSRF token
          'csrfmiddlewaretoken': $('#csrf-token').val()
        },
        success: function(response) {
          // 替换Modal的动态内容
          $('#vulmodal .modal-dialog').html(response);
          // 显示Modal
          $('#vulmodal').modal("show");
        },
        error: function(xhr) {
          console.log('请求出错:', xhr.responseText);
        }
    });
  });
});

4. 调整原有Modal外层模板

保留Modal的基础结构,移除内部静态内容:

<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="vulmodal">
    <div class="modal-dialog modal-lg">
        <!-- 内容将由AJAX动态填充 -->
    </div>
</div>
<!-- 页面中添加CSRF token隐藏域(若JS在单独文件中) -->
<input type="hidden" id="csrf-token" value="{{ csrf_token }}">

额外注意事项

  • 模型中serverity为拼写错误,建议改为severity(需注意数据库迁移兼容性)
  • 可在视图中打印vul_data确认是否查询到有效结果
  • 若使用Bootstrap 5,Modal的触发逻辑需确保与jQuery版本兼容

内容的提问来源于stack exchange,提问作者jonat-han

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:58:12