I have a model that stores a PDF file. On the DetailView of that Model I would like to have a link to view the PDF in a new tab. There are similar questions on here that I've used to get this far, but it looks like they're for local PDFs. My PDFs are stored as Media on AWS.
This is what I have right now:
plans/models.py
class PlanSet(PlanModel):
...
class PlanSetPDF(models.Model):
planset = models.ForeignKey(PlanSet)
PDF = models.FileField(upload_to='planPDFs')
created = models.DateField(auto_now_add=True)
added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
Run Code Online (Sandbox Code Playgroud)
plans/views.py
class PlanSetDetailView(DetailView):
model = PlanSet
template_name = "plan_detail.html"
def get_context_data(self, **kwargs):
context = super(PlanSetDetailView, self).get_context_data(**kwargs)
context['now'] = timezone.now()
return context
def view_pdf(request, pk):
pdf = get_object_or_404(PlanSetPDF, pk=pk)
image_data = open(pdf.PDF.url, "rb").read()
return HttpResponse(image_data, contenttype='application/pdf')
Run Code Online (Sandbox Code Playgroud)
plans/urls.py
urlpatterns = [
url(r'^(?P<pk>\d+)/$', plan_detail, name='detail'),
url(r'^(?P<pk>\d+)/pdf/$', view_pdf, name='view_pdf'),
]
Run Code Online (Sandbox Code Playgroud)
urls.py:
url(r'^plans/', include(plan_sets.urls, namespace='plans')),
Run Code Online (Sandbox Code Playgroud)
template:
{% for pdf in object.plansetpdf_set.all %}
<a href="{% url 'plans:view_pdf' pdf.pk %}">
<span class="glyphicon glyphicon-file" aria-hidden="true"></span>PDF</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
I'm recieving a builtin.OSError:[Errno 22] Invalid Argument: 'https://link_to_PDF_file_on_amazon'
It looks like Python can't open the file. I've looked around and I can't find any answers. Can one of you show me where I'm going wrong? Thanks.
我完全看不出你的view_pdf观点。它所做的只是通过其 URL 打开 PDF,下载它,然后将其重新发送到浏览器。何苦?您应该直接链接到 PDF 的网址;当您这样做时,您可以告诉浏览器在新选项卡中打开它:
<a href="{{ pdf.PDF.url }}" target="_new">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2406 次 |
| 最近记录: |