我目前正在使用Django 1.87开设问题库网站,允许用户登录并查看已保存的过去问题。到目前为止,我已经能够根据用户选择显示数据库中过去问题的链接。过去的问题以文档或PDF格式上传并存储在媒体目录中。
我希望登录用户能够在决定是打印还是下载之前打开并阅读过去问题的内容。到目前为止,我已经能够显示文档的链接列表,当我点击链接时,它将文档下载到我的计算机。我真正想要实现的是用户能够点击链接并在浏览器中打开文档,然后单击下载或在线打印。
这是我的代码:
models.py
class QuestionBank(models.Model):
date = models.DateField(_("Date"),default=date.today)
class_level = models.ForeignKey(ClassLevel)
course_name = models.CharField(max_length=350)
course_code = models.CharField(max_length=20)
question_papers = models.FileField(upload_to = 'Question_Papers/ %y/%m/%d')
views.py def问题(request,sel_course):
context = RequestContext(request)
SelCourse = sel_course.replace('_',' ')
context_dict = {'SelCourse':SelCourse}
try:
Quest_For_course = QuestionBank.objects.filter(course_code = SelCourse)
context_dict['Quest_For_course'] = Quest_For_course
except course_code.DoesNotExist:
pass
return render_to_response('Qbank/QuestionsPage.html', context_dict, context)
在我的模板中我有这个
QuestionsPage.html
<title> Question Papers </title>
<body>
<h2> LIST OF QUESTION PAPERS FOR {{selCourse}} </h2>
<h3> Select question to view, download or print it</h3>
{% if Quest_For_course %}
<ul>{% for ques in Quest_For_course %}
<li><a href="{{ques.question_papers.url}}">
{{ques.question_papers}} </a></li>
{%endfor%}
</ul>
{%else%}
<strong> THERE ARE NO AVAILABLE QUESTION FOR THIS CLASS AT THE MOMENT </strong>
{%endif%}
</body>
如何使过去的问题文档可以查看?在具有下载和打印按钮的表单上。感谢
答案 0 :(得分:0)
如果我返回HttpResponse(file_path)
,它将返回我想要打开的文件的绝对路径。当我运行下面的代码时,我得到:
异常类型:“FileNotFoundError
为什么即使绝对路径正确,python也看不到文件?请帮忙:
def Display(request, file_name):
File_Name = file_name.replace('_', ' ')
file_path = os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name)
with open(file_path,'r') as pdf:
response = HttpResponse(pdf.read(), content_type = 'application/pdf')
response['Content-Disposition'] = 'attachment;filename=some_file.pdf'
return response