在Django中按下按钮时渲染

时间:2020-01-22 09:37:00

标签: python html django

我在Django应用中有一个简单的HTML模板:

...
{% block analyze %}
    <br>
    <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <button type="submit" name="run_script">Run Script</button>
    </form>
    {% if results %}
        <br>
        <a href="data:text/plain;charset=utf-8, {{results}}" download="results.json">download</a>
    {% endif %}
{% endblock %}
...

因此,当我按下按钮时,views.py中的脚本应该激活:

def analysis(request):
    if request.method == 'POST' and 'run_script' in request.POST:
        ...
        # I get the variable finalresults here
        return render(request, 'template.html', {
            'results' : finalresults,
        })
    #in case the button is not pushed, I either want to render to 
    #the template. But without running the script
    return render(request, 'template.html')

我第一次进入那里,就可以了。我按下按钮,它将运行我的脚本。 问题是,当我重新加载页面时,它会自动运行脚本,而无需按下按钮。

我只希望在按下按钮时运行脚本,该怎么办?

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为,当您重新加载页面时,浏览器会记住上一个HTTP方法(POST),并且您发送相同的请求,然后再通过按钮发送。

为解决此问题,您应该将重定向返回到此页面,而不是渲染。

答案 1 :(得分:0)

当您重新加载页面时,我想通过单击浏览器中的“重新加载”按钮,请求会再次发送到django服务器,如果尝试通过重新加载URL而不是通过单击“重新加载”按钮刷新它,它将可以正常工作。 您可以使用按钮上的ajax onclick()来触发对django的请求,而不是POST方法。这将防止页面重新加载。

您可以借助此链接https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

相关问题