我想選擇物件屬性集的第一張影像。我創建了一個帶有 PropertyImages 模型外鍵的屬性模型。如何訪問模板中屬性 object_set.all 的第一張影像。我不想在視圖函式中這樣做,因為它應該在 base.html 檔案中。
代碼:
{% for property in properties %}
<div
style="background-image: url('{{property.propertyimages_set.all|first.url}}'); background-size: 100% 100%; "
;
class="tm-row-featured"
>
<div class="featured-content">
<p><span>Name: </span>{{property.property_name}}</p>
<hr>
<p><span>Type: </span>{{property.property_type}}</p>
<p><span>Price: </span>₦{{property.price}}</p>
<p><span>Location: </span>{{property.property_state}}</p>
<p><a href="{% url 'property_details' property.property_slug %}">More info
>>></a></p>
</div>
</div>
{% endfor %}
uj5u.com熱心網友回復:
您可以使用forloop.first來檢查回圈是否先執行,然后使用適當的 if 標簽來顯示影像。請從下面的鏈接中查看與回圈相關的變數:
參考:https : //docs.djangoproject.com/en/4.0/ref/templates/builtins/#for
{% if forloop.first %}
# Show first image here
{% endif %}
uj5u.com熱心網友回復:
試試這個:
參考
<div style="background-image: url('{{properties.0.propertyimages_set.url}}'); background-size: 100% 100%;"; class="tm-row-featured">
<div class="featured-content">
<p><span>Name: </span>{{properties.0.property_name}}</p>
<hr>
<p><span>Type: </span>{{properties.0.property_type}}</p>
<p><span>Price: </span>₦{{properties.0.price}}</p>
<p><span>Location: </span>{{properties.0.property_state}}</p>
<p><a href="{% url 'property_details' properties.0.property_slug %}">More info >>></a></p>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389597.html
標籤:Python 姜戈 django 模型 django-模板
