<p>在谷歌搜索了几天后,我设法拼凑出这个问题的一些解决方案,这是我的项目所需要的。</p>
<p>斯旺克斯瓦什巴克勒给出了一般的方法,我只是想加入它来完成这个循环。这可能不是唯一的解决方案,所以我只举了一个有效的例子。所以。。您的模板应包含以下代码(如上所述以及一些附加代码):</p>
<p><strong>您的模板.html</strong></p>
<pre><code>{% 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 %}
</code></pre>
<p>如果您在forms.py中定义了表单和/或使用模型进行表单呈现,那么请检查呈现的HTML,以了解Django在表单中呈现的“value”属性是什么“值”是将在您的POST请求中提交的内容。</p>
<p>您定义的视图将显示表单,并在提交后对其进行处理,因此您将在其中包含两个带有“if”语句的部分。
Django使用“GET”打开视图,因此初始呈现显示空白表单</p>
<p><strong>视图.py</strong></p>
<pre><code>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])
</code></pre>
<p><strong>表单.py</strong></p>
<pre><code>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()
</code></pre>
<p>当您调用<strong>form=your_form_name()</strong>时,“info_text”将在模板中呈现为“input”字段。有关Django表单的更多信息,请参见<a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/forms/fields/</a></p>
<p>当您按submit时,表单会将数据提交回自身,因此您的视图将选择其文章并运行<strong>是有效的,然后<strong>输出的值将是<strong>子流程返回的错误代码。检查调用。如果脚本运行正常,“output”的值将为“0”。</p>
<p>这是“Django 1.4”和“Python 2.6”。最新版本有<strong>子流程。请选中“输出”,它实际上可以返回脚本的输出,以便您可以将其重新呈现在模板上。</p>
<p>希望这有帮助:)</p>