我最近開始學習 Django,我也是 Web 開發的新手。我面臨 Django 不加載影像但加載 CSS 和 JS 檔案的問題。我已經完成了 Django 檔案中所示的設定,并且還參考了許多 youtube 視頻。我的設定幾乎相同。但靜止影像沒有加載。下面是我的虛擬環境的 Pip 凍結
(venv) PS E:\django\myproject> pip freeze
asgiref==3.4.1
Django==3.2.8
pytz==2021.3
sqlparse==0.4.2
下面是我的 Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
HTML
{%for product in products %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{% static 'products/images/flour.png' %}" alt="No Image">
<div class="card-body">
<h5 class="card-title">{{product.product_name}}</h5>
<p class="card-text">{{product.product_description | default:"Nothing"}}</p>
<a href="/products/{{product.id}}" class="btn btn-primary">Update</a>
</div>
</div>
{%endfor%}
檔案夾結構
myproject
- settings.py
- urls.py
products
- static
- Products
- images
- flour.jpg
- templates
- base.html
- **products.html** #Image is to be loaded in this page
- models.py
- urls.py
- views.py
控制臺中的錯誤控制臺中的 錯誤 如果需要更多資訊,請告訴我 提前致謝
以下是來自服務器的日志
System check identified no issues (0 silenced).
October 29, 2021 - 13:02:41
Django version 3.2.8, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
{'products': <QuerySet [<Product: 120010>]>}
[29/Oct/2021 13:02:45] "GET /products/ HTTP/1.1" 200 1796
[29/Oct/2021 13:02:45] "GET /static/Products/styles/app.css HTTP/1.1" 200 40
[29/Oct/2021 13:02:45] "GET /static/products/scripts/app.js HTTP/1.1" 200 117
[29/Oct/2021 13:02:45] "GET /static/products/images/flour.png HTTP/1.1" 404 1935
uj5u.com熱心網友回復:
1確保在 html 頂部有 load static 標簽
2嘗試將此附加到您的網址(附加到主 urls.py 以及應用程式網址以防萬一)
from django.contrib import admin
from django.urls import path,include
**#These two lines and the last line after square bracket**
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('homepage.urls') ),
path('register/', include('registration.urls') ),
path('dashboard/', include('dashboard.urls') ),
path('teams/', include('team.urls') ),
path('matches/', include('match.urls') ),
] static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340991.html
