我正在使用Django v1.4(Python v.2.7.3),我正在尝试构建一个校验应用程序。我的校对程序有一个“示例”页面,其中包含一个指向用户示例校样的链接列表,这些链接一个接一个地在屏幕上呈现。一小部分样本如下所示:
这些示例文件保存在服务器上的MEDIA_ROOT中,我想要的是一种方法,以便单击该链接将POST文件中的文件内容传递给特定视图。该视图已经设计了用于处理用户直接从其文件系统上传校样文件的代码,因此基本上我想要做的是使example.html模板(如下所示)传递除文件之外的相同类型的信息已存储在服务器上。
examples.html的代码是:
{% load staticfiles %}
<html>
<head>
<title>Anaconda</title>
<style>
body
{
overflow-y: scroll;
}
</style>
</head>
<body>
<center>
<a href="/server"><img src="{% static "AnacondaTitleText.png" %}" alt="Title" height="40%" width="40%"/></a>
<div align="left" style="width:800px;">
<h2>Anaconda Examples</h2>
<p>You can click the button beside each example on this page to load it into the proof window.
{% if examples %}
The following examples are included with Anaconda:</p>
<br>
{% for example in examples %}
<p>{{ example.exampleFile.name|cut:"./" }}: <a href="{{ example.exampleFile.url }}">link</a></p>
<br>
{% endfor %}
{% else %}
There are no examples currently included with Anaconda.</p>
{% endif %}
</div>
</center>
</body>
</html>
“a href ...”部分需要更改,因为目前点击它会弹出一个“保存文件”对话框,这不是我想要的。
在我的服务器的views.py文件中,我有以下代码能够处理上传的文件:
def proof(request):
if request.method == 'POST':
defaultText = request.FILES['docfile'].read()
proofText = ProofForm(request.POST)
else:
defaultText = ""
proofText = ProofForm()
c = {}
c.update(csrf(request))
c['form'] = proofText
c['default_text'] = defaultText
return render_to_response('server/proof.html', c)
我想我想要的是一种方法来做到以下几点:
我的models.py文件如下所示:
from django.db import models
class Example(models.Model):
exampleFile = models.FileField(upload_to='.')
如有必要,我很乐意提供更多信息。
答案 0 :(得分:0)
我找到了解决方案,但我怀疑它有点hacky。
在examples.html中,我包含以下内容:
{% for example in examples %}
<form name="example" action="/server/proof" method="post">
{% csrf_token %}
<p>{{ example.exampleFile.name|cut:"./" }}</p>
<input type="hidden" name="example" value="{{ example.exampleFile.name|cut:"./" }}">
<input type="submit" value="Select">
</form>
<br>
{% endfor %}
我将文件的名称与隐藏的输入元素相关联,然后在views.py中我有以下代码:
def proof(request):
if request.method == 'POST':
print "DATA"
print str(request.POST)
try:
defaultText = request.FILES['docfile'].read()
except:
examplePath = request.POST.get('example')
with open(join(MEDIA_DIR, examplePath), 'r') as f:
defaultText = f.read()
proofText = ProofForm(request.POST)
else:
defaultText = ""
proofText = ProofForm()
c = {}
c.update(csrf(request))
c['form'] = proofText
c['default_text'] = defaultText
return render_to_response('server/proof.html', c)
这是拼凑而成,但它做了我想要的。希望我稍后会有时间改进代码。