在django中显示pdf文件

时间:2018-02-23 07:29:29

标签: django python-3.x django-models django-rest-framework

嗨,当用户点击我需要显示pdf文件时,我是django框架的新手 我正在使用的代码是

with open(file_path+file_name, 'rb') as pdf:
    response = HttpResponse(pdf.read(), mimetype='application/pdf', contenttype='application/pdf')
    response['Content-Disposition'] = 'inline;filename=some_file.pdf'

我得到的错误是

File "/usr/local/lib/python3.4/dist-packages/rest_framework/viewsets.py", line 90, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/tritwdapp/tribalwelfare/inspection/inspectdataview.py", line 290, in getSubmitReport
    response = HttpResponse(pdf.read(), mimetype='application/pdf',contenttype='application/pdf')
  File "/usr/local/lib/python3.4/dist-packages/django/http/response.py", line 283, in __init__
    super(HttpResponse, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'contenttype'

任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

试试这个:

def pdf_view(request):
    with open('file.pdf', 'r') as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response

mimetype已被content_type取代。它已在Django 1.7中删除。另外,你拼错了。 请注意,这样的解决方案并非最佳。通常,出于性能原因,您的Web服务器将提供这些文件。

相关问题