[英]Show only link to file which exists Django Python
我的 models.py 中有四個 FileFields,如下面的 2:
file_1 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 1")
file_2 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 2")
每次上傳不同數量的文件,有些是空的。 我在 my.html 頁面中使用以下內容來提供上傳文件的下載選項:
<p class="article-content mb-1"><strong>Datoteka 1: </strong><a href="{{post.file_1.url}}" download>Preuzmi</a></p>
<p class="article-content mb-1"><strong>Datoteka 2: </strong><a href="{{post.file_2.url}}" download>Preuzmi</a></p>
問題是,我有 4 個上傳選項,如果有些沒有使用,我會收到以下錯誤:
The 'file_2' attribute has no file associated with it
如果文件不存在,如何在頁面上生成空字段(.destroy、.remove)之前抑制它們? 我想我必須使用 javascript? 如何檢查而不顯示
如果文件不存在?
JavaScript 在這里對您沒有幫助,因為在渲染期間發生在服務器端的錯誤。 您可以簡單地將文件的 HTML 放在if
模板標簽 [Django docs]中:
{% if post.file_1 %}
<p class="article-content mb-1"><strong>Datoteka 1: </strong><a href="{{post.file_1.url}}" download>Preuzmi</a></p>
{% endif %}
{% if post.file_2 %}
<p class="article-content mb-1"><strong>Datoteka 2: </strong><a href="{{post.file_2.url}}" download>Preuzmi</a></p>
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.