Django 模板 - 来自 media_root 的图像在首页呈现,但在其他页面不呈现
Django templates - Image from media_root rendered in homepage, but not other pages
我有一张图片呈现在我的主页上,但它没有出现在使用相同代码的不同页面上。我认为问题可能是我的 url 路径不同?这是我能找到的唯一区别。当我检查每个元素时,这是我看到的:
Working image: /event/image.png
Broken Image: /event/media/image.png
我正在我的模板中渲染图像:
<img src="media/{{event.image}}" class="img-responsive" />
我的模型只是一个 model.Image 字段,这是我对损坏图像页面的看法:
def event(request, product_id):
event = get_object_or_404(Event, id=product_id)
image = event.image
context = {'event':event, 'image':image}
template = 'tourney.html'
return render(request, template, context)
在我的终端中,它说找不到图像。那么,如何更改我的设置,以便无论我在哪个路径中,它都会在正确的目录中查找?这是我的媒体设置:
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static-only')
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'media')
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), 'static', 'static'),
)
您需要一个前导斜线:“/media/...”。
但是,更好的方法是使用 built-in 属性,它可以为您提供完整的 URL,包括 MEDIA_URL:
<img src="{{ event.image.url }}" class="img-responsive">
与其像 media/{{event.image}}
那样自己构建 url,不如让 Django 为您完成这项工作:
<img src="{{ event.image.url }}" class="img-responsive" />
这样,Django 将使用您设置中的 MEDIA_URL
创建适当的 URL。请注意,您的网络服务器配置必须与之匹配,并在 MEDIA_URL
上提供来自 MEDIA_ROOT
的图像
我有一张图片呈现在我的主页上,但它没有出现在使用相同代码的不同页面上。我认为问题可能是我的 url 路径不同?这是我能找到的唯一区别。当我检查每个元素时,这是我看到的:
Working image: /event/image.png
Broken Image: /event/media/image.png
我正在我的模板中渲染图像:
<img src="media/{{event.image}}" class="img-responsive" />
我的模型只是一个 model.Image 字段,这是我对损坏图像页面的看法:
def event(request, product_id):
event = get_object_or_404(Event, id=product_id)
image = event.image
context = {'event':event, 'image':image}
template = 'tourney.html'
return render(request, template, context)
在我的终端中,它说找不到图像。那么,如何更改我的设置,以便无论我在哪个路径中,它都会在正确的目录中查找?这是我的媒体设置:
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static-only')
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'media')
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), 'static', 'static'),
)
您需要一个前导斜线:“/media/...”。
但是,更好的方法是使用 built-in 属性,它可以为您提供完整的 URL,包括 MEDIA_URL:
<img src="{{ event.image.url }}" class="img-responsive">
与其像 media/{{event.image}}
那样自己构建 url,不如让 Django 为您完成这项工作:
<img src="{{ event.image.url }}" class="img-responsive" />
这样,Django 将使用您设置中的 MEDIA_URL
创建适当的 URL。请注意,您的网络服务器配置必须与之匹配,并在 MEDIA_URL
MEDIA_ROOT
的图像