python - 如何配置 django 媒体文件夹?
问题描述
我有 Django v 3.0。我的要求。我尝试打开媒体链接,但出现路径/文件不存在的错误。在我的 settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_ROOT = os.path.join(BASE_DIR, "assets")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'assets', 'media')
STATIC_URL = '/assets/'
STATICFILES_DIRS = [
STATIC_DIR,
]
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
我的网址.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我不知道该怎么做,需要你的帮助
解决方案
尝试更改您的配置。这是放置问题,您不应该在 STATICFILES_DIRS 之前定义媒体根和 url。
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_ROOT = os.path.join(BASE_DIR, "assets")
STATIC_URL = '/assets/'
STATICFILES_DIRS = [
STATIC_DIR,
]
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
# place this code end of setting
MEDIA_ROOT = os.path.join(BASE_DIR, 'assets', 'media')
MEDIA_URL = '/media/'
推荐阅读
- npm-install - 编译失败错误
- c# - 每 X 秒读取一次串口
- python - 代码中的错误(只有整数标量数组可以转换为标量索引)
- reactjs - 当 HTML 元素存在时 toContainHTML 提供错误(反应测试)
- python - 实例之间的 PyQt Signal Slots 连接
- node.js - express js:端口正在运行但无法终止端口
- c++ - 介子在调试模式下编译子项目
- javascript - 我不明白为什么我的消息没有发送给每个决定收到通知的用户。它只发送给一个
- visual-studio-code - 连接 FTP 帐户时出现 FTP 关闭消息
- list - 在颤动中从列表中添加和删除对象