所以我有 5 張影像作為靜態檔案,我想在按下按鈕時隨機選擇要顯示的影像。我在獲取影像名稱更新時遇到問題。當我將名稱硬編碼到 html 中時,它確實有效。
在我看來,我有:
def test(request):
imagename = 'img' str(random.randint(0,5)) '.jpeg' #all the images end with jpeg so this can't be the problem
print(imagename)
return render(request, 'mainbook/index.html', {'image': imagename})
在 urls.py 我有
urlpatterns = [path('test/', views.test, name='test')]
最后在 index.html 我有:
<form method="post" action="{% url 'mainbook:test' %}">
{% csrf_token %}
<button id="button">Press here</button>
</form>
<img src="{% static '/mainbook/images/{{image}}' %}"></img>
這當然是一個簡化版本,但我確實認為問題出在這段代碼的某個地方。我只是不知道具體在哪里。
uj5u.com熱心網友回復:
您正在嘗試關閉一個 img 標簽,并且您不能在“{% %}”中使用“{{ }}”
從:
<img src="{% static '/mainbook/images/{{image}}' %}"></img>
至:
<img src="{% static '/mainbook/images/{{image}}' %}">
然后:
<img src="{% static '/mainbook/images/{{image}}' %}">
至:
<img src="{% static '/mainbook/images/' %}{{image}}">
應該管用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/487503.html
