【问题标题】:Folder for static images can't be accessed/found无法访问/找到静态图像的文件夹
【发布时间】:2021-04-05 07:09:18
【问题描述】:

我尝试关注 this 或 this 或 this 但对我没有任何作用 - 我有一个名为 media 的目录,其中已上传文件 - 但我无法使用 http://127.0.0.1:8000/media/ 访问它 - 页面不找到 (404)。

我的设置.py:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'PROJECT/static'),
]

MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
MEDIA_URL = "/media/"

还有我的 urls.py:

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView, 
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('home/', RedirectView.as_view(url='/')),
    path('admin/', admin.site.urls),
    path('', include('appname.urls')),
    path('', include('django.contrib.auth.urls')),
    path(r'^login', auth_views.LoginView.as_view(template_name='registration/login.html')),
]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

额外的问题,因为直到现在我都无法尝试:如何在模板中的 /media/ 中访问带有 filename.jpg 的图像?

我通过反复试验解决了这个问题:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'projectname/static'),
]

MEDIA_ROOT = os.path.join(BASE_DIR, "projectname", "media")
MEDIA_URL = "/media/"

【问题讨论】:

  • 在 settings.PY 中,DEBUG 是否设置为 true?
  • 看来你做得很好。除了:您是否试图通过一些文件最终到达127.0.0.1:8000/media(127.0.0.1:8000/media/filname.png)?或者就像你在问题中展示的那样?如果它像有问题(127.0.0.1:8000/media),它会给你404,因为没有文件作为“”空字符串。
  • 是的,调试设置为true。
  • 当我尝试转到 http://127.0.0.1:8000/media/test.bmp 时,我仍然得到 404(文件在文件夹 media 中)。
  • 虽然很有趣 - print(MEDIA_ROOT) 结果是 C:\Users...\projectname\media/ - 见最后一个斜线。省略它并没有帮助。

标签: django django-templates django-staticfiles


【解决方案1】:

试试效果

your_app urls.py

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
   ....
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

STATIC_URL = "/static/"
STATICFILES_DIRS = (
  os.path.join(BASE_DIR, "static")
)
STATIC_ROOT = (
  os.path.join(BASE_DIR, "staticfiles")
)

MEDIA_URL = "/media/"
MEDIA_ROOT = (
  os.path.join(BASE_DIR, "media")
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2018-12-30
    • 2013-11-04
    相关资源
    最近更新 更多