我是django的初学者。我正忙着一个用户可以提交论文的网站。那么审稿人(其他用户)以及提交论文的用户应该能够下载提交的论文(用于编辑和评分)吗?我如何做到可能?上传文档时,它为我提供了一个链接,该链接是存储文件的文件路径。当我点击它时,它只显示一条404消息,很明显我没有一个带有该文件路径的网页或URL。我该如何解决这个问题?
更新
我见过django提供的path()
函数,但我不确定在哪里使用它?
更新
好的,所以我编辑了我的views.py文件,看起来像这样
def returnDoc(request):
# This function get the documents of all the users and the in the html displays only the logged in authors submitted papers.
doc = Document.objects.all()
user = RegUser.objects.all()
status = user
return render_to_response('user_profiles/profile.html', {'doc':doc, 'status':status}, context_instance=RequestContext(request))
def download_paper(request, paper_pk):
# Document is the model with the FileField.
paper = get_object_or_404(Document, pk=paper_pk)
with paper.pdf_file_field.open("r") as fd:
response = HttpResponse(fd.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename="%s"' % paper.pdf_file_field.title
return response
然后我的模板如下:
`
<p class="well"> Here you should be able to see any information regarding your submitted papers, including any reviews that have been made on these papers
and the status of your paper as "accepted" or "rejected". Please note that all decisions made are final. </p>
<div class="jumbotron">
<h2> Paper Submissions </h2>
<!-- Display an author's papers (if they have any -->
<table class="table table-hover">
<thead>
<tr>
<th> Paper Title </th>
<th> Institution </th>
<th> Abstract </th>
<th> File </th>
<th> Reviews* </th>
<th> Avg. Score </th>
<th> </th>
</tr>
</thead>
<!-- Iterate through each element of the Document() model and output each element in a table cell-->
{% for item in doc %}
{% if request.user == item.author %}
<tr>
<td> {{ item.title }}</td>
<td> {{ item.institution }} </td>
<td> {{ item.abstract }} </td>
<td> <a href="{{MEDIA_URL}}{{item.file}}" target="_blank"> {{item.title}}</a></td>
<td> N.A </td>
<td> */10 </td>
<td> <a href="#"> Edit Paper </a>
</tr>
{% endif %}
{% endfor %}
`
我不确定"{{MEDIA_URL}}{{item.file}}"
是否应该在那里,因为它只是将我重定向到URL本身的文件路径。我应该把它拿出来吗?
提前谢谢
答案 0 :(得分:1)
上传文件的“安全”下载是通过视图完成的。 (另一种方法是让Web服务器为所有上传的文件提供一些前缀,就像你提供任何静态文件一样。缺点是你失去了对文件的所有访问控制。任何人都可以阅读它们。)
您可以将文件作为响应发送到客户端,而不是呈现模板。 (假设您使用的是FileField)。例如:
def download_paper(request, paper_pk):
paper = get_object_or_404(Paper, pk=paper_pk) # get your model instance
# also check permissions on paper, if necessary
with paper.pdf_file_field.open("r") as fd:
response = HttpResponse(fd.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename="%s"' % paper.pdf_file_field.name
return response