2017-04-06 126 views
1

我目前正在使用Django 1.87开发一个问题银行网站,它允许用户登录并查看保存的过去问题。到目前为止,我已经能够根据用户选择在数据库中显示过去问题的链接。过去的问题将以文档或PDF格式上传并存储在媒体目录中。Django如何打开并显示保存的docx或pdf文档

我希望登录的用户能够在决定是打印还是下载之前打开并阅读过去问题的内容。到目前为止,我已经能够显示文档的链接列表,当我点击链接时,它将文档下载到我的电脑。我真正想要达到的目的是使用户能够单击链接并从浏览器中打开文档,然后单击此处的下载扩展器代码或打印。

这里是我的代码:

models.py

试题库类(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 画质问题(要求,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

看看这个 - http://stackoverflow.com/questions/39919012/django-python-show-pdf-in-a-template – Compadre

+0

@Compadre我非常感谢这个推荐的链接,它真的有助于澄清我很困惑的事情。但现在我面临着另一个挑战和驱动坚果,因为已经尝试了很多方法来获得文件工作的绝对路径,我很困惑,不知道还有什么要做。这里是我所做的 – jids

+0

有人应该请帮助我,我坚持我不知道还有什么要尝试。这里的代码给了我想要输出的文件的绝对路径file_path = os.path.join(settings.MEDIA_ROOT,'QuestionPapers',File_Name)但我仍然得到FileNotFoundError – jids

回答

0

如果我返回HttpResponse(file_path),它将返回我想要打开的文件的绝对路径。当我运行下面的代码,我得到:

异常类型:?“FileNotFoundError

为什么蟒没有看到文件,即使在绝对路径是正确的请帮忙:

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 
相关问题