【问题标题】:change context after the response in sent in django在 django 中发送响应后更改上下文
【发布时间】:2021-01-18 02:42:07
【问题描述】:

我有一个 django 视图,我希望上下文中的一些数据每秒更改几次。我可以在发送响应后将新上下文加载到模板中而不发送新请求吗?谢谢。

视图

def debug(request):
    return render(request, 'all/debug.html', context={"x": x, "y": y})

模板

<div class="container">
    <canvas id="data"></canvas>
    <div class="graphing">
    <select class="graph-select"></select>
    <canvas id="graph" width="500"></canvas>
    </div>
</div>

<script>
    let y = "{{ y }}";
    let x = "{{ x }}"
    Chart.defaults.global.animation.duration = 0;
    var ctx = document.getElementById('graph').getContext('2d');
    var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'line',

        // The data for our dataset
        data: {
            labels: x.split` `.map(n => +n),
            datasets: [{
                label: 'My First dataset',
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: y.split` `.map(n => +n)
            }]
        },

        // Configuration options go here
        options: {
            responsive: false,
        }
    });

</script>

我想要的是在不发送新请求的情况下动态更改 x 和 y 数据

【问题讨论】:

  • this 回答你的问题了吗?
  • @Sashaank 是的,确实如此。我最终(经过比预期更多的工作)能够让它发挥作用。谢谢!

标签: python django web


【解决方案1】:

您应该在模板中使用 ajax 技术。 here你可以找到一些信息。

【讨论】:

    【解决方案2】:

    只需将视图更改为此 `

    -

    if somthing happens :
        return render(request, 'all/debug.html', context={"z": z, "t": t})
    else:
        return render(request, 'all/debug.html', context={"x": x, "y": y})
    return render(request, 'all/debug.html', context={"x": x, "y": y})
    

    `

    【讨论】:

    • 是的,但我还是退回了它。问题是我无法更改数据之后返回响应
    • @AdarMaori 请描述响应的去向是从模板到 django 视图还是相反
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多