【问题标题】:I could not point correctly the static image files我无法正确指向静态图像文件
【发布时间】:2021-12-19 12:20:32
【问题描述】:

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.pyMain_Project文件夹下

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)

我的项目目录

Main_Project (top)
--Main_Project (top)
  --settings
  --urls
--pizza 
  --static
    --Pizza
      --(images)
   --templates
   --migrations
   --views.py
   --models.py
   --urls.py

在这个 Django 项目中,我对静态图像和文件应该放在哪里感到困惑,因为我无法加载我保存在静态文件夹目录中的 index.html 中的图像。此外,我不确定我的设置是否正确以便在模板上显示图像,但是当我尝试打印 pizza_list 时,它可以显示图像文件名。请问什么是最好的文件夹结构才能让模板识别静态文件夹中的图像文件来显示?

【问题讨论】:

  • 尝试在你的 html 中输入 {{ Pizza }} 标签,看看它是否真的呈现了一个正在唱歌的 Pizza 对象的拍子。我建议在这种情况下使用 ListView CBV
  • 首先你应该在浏览器中看到 HTML,看看你在这个 HTML 中创建了哪些 url。 os.listdir(folder) 仅提供文件名,您可能需要在文件名中添加 folder 以创建完整路径。

标签: python html django web


【解决方案1】:
  1. 您是否{% load static %}?

  2. 我假设 {{ Pizza }} 变量是一个图像。如果是这样,请使用:

<img src="{% static 'Pizza/{{ pizza.url }}' %}" />

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 2020-07-21
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多