简体   繁体   English

django - 将模型的文件呈现给模板

[英]django - render a file of a model to template

I have a model called Advertisement. 我有一个名为广告的模型。 This model has text field, title field, and file field. 此模型具有文本字段,标题字段和文件字段。

I am successfully saving all 3 of these fields into the model. 我成功地将所有这三个字段保存到模型中。

Now I need to show them in template. 现在我需要在模板中显示它们。 My vision is: 我的愿景是:

ads = Advertisement.objects.all()
return render_to_response('page.html', {'ads':ads},context_instance=RequestContext(request))

and in my page.html: 并在我的page.html中:

{% for each_ad in ads %}
<p>{{each_ad.title}}</p>
<p>{{each_ad.text}}</p>
<p><a href="/ads/{{each_ad.file_pdf}}>{{each_ad.file_pdf.name}}</a></p>
{% endfor %}

Does this seem right? 这看起来是对的吗? If not, please show me the way so I can learn. 如果没有,请告诉我我可以学习的方式。 Thanks! 谢谢!

Whether the PDF link downloads depends on the browser of the user. PDF链接是否下载取决于用户的浏览器。

Adding target="_blank" will open the pdf in a new window/tab though: 添加target="_blank"将在新窗口/选项卡中打开pdf:

<p><a href="/ads/{{each_ad.file_pdf}}" target="_blank">{{each_ad.file_pdf.name}}</a></p>

To ensure that it always downloads in every environment is more difficult, you would need to set your .htaccess (if you're using apache, per something like this: Force a file or image to download using .htaccess ) or force it as an attachment in producing the PDF from Django. 要确保它始终在每个环境中下载都比较困难,您需要设置.htaccess (如果您使用的是apache,请执行以下操作: 使用.htaccess强制下载文件或图像 )或强制它为从Django生成PDF的attachment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM