[英]Render while pushing a button in Django
I have a simple HTML template in a django app:我在 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 %}
...
So when I push the button, the script in views.py should activate:所以当我按下按钮时,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')
The first time I enter there, it works.我第一次进入那里时,它起作用了。 I push the button, and it runs my script.
我按下按钮,它运行我的脚本。 The problem is, when I reload the page, it automatically runs the script, without pushing the button.
问题是,当我重新加载页面时,它会自动运行脚本,而无需按下按钮。
I just want the script to be run when I press the button, how could I do that?我只想在按下按钮时运行脚本,我该怎么做?
It happens because when you reload page, browser remember last HTTP method (POST) and you send same request then you send by button.发生这种情况是因为当您重新加载页面时,浏览器会记住最后一个 HTTP 方法(POST)并且您发送相同的请求然后您通过按钮发送。
For resolving this problem you should return redirect to this page instead of render.为了解决这个问题,你应该返回重定向到这个页面而不是渲染。
When you reload the page,I guess by clicking the reload button in the browser the request is sent again to the django server,if you try by reloading the URL and not refreshing it by clicking the reload button, it will work fine.当您重新加载页面时,我想通过单击浏览器中的重新加载按钮,请求会再次发送到 django 服务器,如果您尝试重新加载 URL 而不是通过单击重新加载按钮刷新它,它将正常工作。 You can use ajax onclick() on the button to trigger a request to django,instead of POST method.This will prevent page reloading.
您可以在按钮上使用 ajax onclick() 来触发对 django 的请求,而不是 POST 方法。这将阻止页面重新加载。
You can take help of this link https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html您可以使用此链接https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.