Django admin:图像已保存但单击时发生错误

Django admin: image saved but error occured when click

我很惭愧问这样的问题,但我仍然无法解决我的问题。我通常在我的媒体目录中上传图像,并且可以在我的管理中看到图像 link 但是如果我点击 link 我得到:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/photo/img/9.jpg Using the URLconf defined in TeamStudy.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, photo/img/9.jpg, didn't match any of these. my project structure:

src
static/
      photo/ 
           img/

设置:

PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)

MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'photo')
MEDIA_URL = '/photo/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_URL = '/static/'

urls.py

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
]

我怀疑它可能很简单,但我错过了一些东西。请指点我

更改 URL 的模式:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

了解更多信息Django Docs

您需要在 urlpatterns 中添加媒体 MEDIA_ROOTMEDIA_URL

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

查看以下链接了解更多详情

Accessing "Media" files in Django

Django 将用户文件分为两种类型

  1. 静态文件
  2. 媒体文件

this link帮你理解它们的区别

您的问题涉及媒体文件。

In future development, you may need to serve static files, to serve them you will need to add STATIC_ROOT and STATIC_URL to the urlpatterns in a similar way that MEDIA_ROOT and MEDIA_URL are added

第一点:不要将上传的媒体文件放在您的 static 目录中 - static 用于项目中的静态文件(css、js 等)-、你想为此使用 MEDIA_ROOTMEDIA_URL

wrt/ 提供静态和媒体内容,这取决于环境。在您的本地开发环境中,您希望使用 staticfile.views 为其他答案中提到的静态和媒体提供服务,但是 不要在生产中这样做 :在生产中服务器,您想使用前端 Web 服务器来提供静态(和媒体)内容。