index.html
<div class="carousel-inner" role="listbox">
{% for pizza in pizza_list %}
{% if forloop.counter0 == 0 %}
<div class="carousel-item active">
<img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="...">
</div>
{% else %}
<div class="carousel-item">
<img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="...">
</div>
{% endif %}
{% endfor %}
</div>
views.py
def index(request):
pizza_list = []
print(os.getcwd())
for item in os.listdir('static/Pizza'):
pizza_list.append(item)
## print(pizza_list)
context = {'pizza_list':pizza_list}
return render(request,'index.html',context)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
urls.py under Main_Project
folder
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('pizza.urls')),
]
urlpatterns = static(
settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
My project directory
Main_Project (top)
--Main_Project (top)
--settings
--urls
--pizza
--static
--Pizza
--(images)
--templates
--migrations
--views.py
--models.py
--urls.py
In this Django project, I have a confusion about where should the static images and files put under because I could not load the image in index.html
that I saved in the static folder directory. Also, I am not sure whether my settings are correct in order to have the images shown on the templates but when I tried to print pizza_list
it could show the image file names. May I ask what is the best folder structure in order to have the templates recognize the image files in static folder to display?
CodePudding user response:
Did you {% load static %}?
I assume the {{ pizza }} variable is an image. If so then use this:
<img src="{% static 'Pizza/{{ pizza.url }}' %}" />