I started learning Django recently and I am also new to Web development. I am facing an issue with Django not loading images but loading CSS and JS files. I have done the setup as shown in Django documentation and also referred to many youtube videos. My setup is almost the same. But still images are not loading. Below is the Pip freeze of my virtual environment
(venv) PS E:\django\myproject> pip freeze
asgiref==3.4.1
Django==3.2.8
pytz==2021.3
sqlparse==0.4.2
Below is my 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%}
Folder Structure
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
Error in console Error in console Please let me know if anything more required Thanks in advance
Below is the log from server
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
CodePudding user response:
1 Make sure you have the load static tag in the top of the html
2 Try attaching this to your url ( to the main urls.py and also the apps urls just in case )
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)