在谷歌上搜索了几天后,我设法就这个问题拼凑了一些解决方案,这是我的项目所需要的。
SwankSwashbucklers 给出了一般方法,我只是想添加它以完成循环。这可能不是唯一的解决方案,所以我只给出一个工作示例。所以..你的模板应该包含以下代码(如上所示,还有一些额外的):
your_template.html
{% extends base.html %}
{% block main_content %}
<form action="your_view_url" method="post">{% csrf_token %}
{{ form.as_table }}
// <input type="text" name="info_name" value="info_value">
<input type="submit" value="Submit">
</form>
<p> Post Data: {{ info }} </p>
<p> Result: {{ output }} </p>
{% endblock main_content %}
如果您在 forms.py 中定义了您的表单和/或使用您的模型进行表单呈现,那么检查呈现的 HTML 以找出 Django 在表格。 “值”是您的 POST 请求中将提交的内容。
您定义的视图将显示表单,并且在提交后也会对其进行处理,因此您将在其中包含 2 个带有“if”语句的部分。
Django使用“GET”打开视图,所以初始渲染显示空白表单
views.py
import subprocess
def your_view_name(request):
if request.method == 'GET':
form = your_form_name()
else:
if form.is_valid():
info = request.POST['info_name']
output = script_function(info)
// Here you are calling script_function,
// passing the POST data for 'info' to it;
return render(request, 'your_app/your_template.html', {
'info': info,
'output': output,
})
return render(request, 'your_app/your_template.html', {
'form': form,
})
def script_function( post_from_form )
print post_from_form //optional,check what the function received from the submit;
return subprocess.check_call(['/path/to/your/script.py', post_from_form])
forms.py
class your_form_name(forms.Form):
error_css_class = 'error' //custom css for form errors - ".error";
required_css_class = 'required' //custom css for required fields - ".required";
info_text = forms.CharField()
当您调用 form = your_form_name() 时,“info_text”将在模板中呈现为“输入”字段中的内容。更多关于 Django 表单的信息在这里https://docs.djangoproject.com/en/1.9/ref/forms/fields/
当您按下提交时,表单会将数据提交回自身,因此您的视图会选择它是一个 POST 并运行 is_valid ,然后是 output 的值strong> 将是 subprocess.check_call 返回的错误代码。如果您的脚本运行正常,“输出”的值为“0”。
这适用于“Django 1.4”和“Python 2.6”。最新版本具有 subprocess.check_output,它实际上可以从脚本返回输出,因此您可以将其渲染回模板上。
希望这会有所帮助:)