好的,让我们再试一次。
我的 Django 图像未显示在我的模板中。尽管设置正确。
这是我的设置 - 一个完全可复制的设置 - 如下:
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#urls.py
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.views.static import serve
urlpatterns = [
path('<uuid:uuid>', views.details),
]
# Only for development. Do not use this in production.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
#views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import MediaModule
def details(request, uuid):
articles = MediaModule.objects.all().values()
article = get_object_or_404(MediaModule, uuid=uuid)
title = article.article_headline
return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles})
#media-article.html
<img src="{{article.article_image.url}}" alt="{{article.article_image.url}}"/>
#models.py
from django.db import models
import uuid
# Create your models here.
class MediaModule(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
article_image = models.ImageField(upload_to='static/assets')
这是我的文件目录布局:
ProjectName-|
RootFolder-|
settings.py
media-| #app name
templates-|
media-article.html
models.py
views.py
urls.y
static-|
assets-|
image.jpg
当我进入浏览器中的调试控制台时,是否有一个有效的理由 - 尽管
src
指向 /static/assets/118118money_u1wgRGw.jpg
的正确目录,但它是否给了我 404 错误
为什么?!
是的,在写这篇文章之前我已经看过这里的其他帖子。
我真的花了整个下午的时间来处理这个问题,现在我正在认真地寻找我的耐心。我已经尝试了一切,我添加了斜杠,我删除了斜杠,我更改了目录,我重新配置了控制器,我尝试了绝对 URl'S,我尝试了相对 URL,我已经删除了图像并读取了它们,我可以确认并且尽管图像位于正确的目录中并且我的配置是正确的,但还是再次确认了
settings.py, and I have confirmed then again. I have gone into the inspect source code and the URL directory is correct, I go to the director and guess what,
error404`。
Everting 是正确的,但我只是无法显示这些图像。我非常生气,我很生气。
Project-|
media-| #app
templates-|
apps.py
models.py
views.py
urls.y
media-article.html
media-|
assets-|
image.jpg
project-| #main app
settings.py
urls.py
asgi.py
wsgi.py
所以你需要从 media/urls.py 中删除它
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
并将其放入项目(主应用程序)/urls.py 如果您在此处包含了媒体应用程序的路径,您最好重命名上传媒体的路径(例如/media-upload)