Django Media url returns 404 未找到
Django Media url returns 404 NOT FOUND
我有一个 Django 项目。
为了设置我的媒体 url,我遵循了 django 文档 Django doc - Managing static files:
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我的 settings.py:
# ....
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = 'http://127.0.0.1:8000'
# ...
MEDIA_URL_REL = '/media/'
MEDIA_URL = BASE_URL + MEDIA_URL_REL
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
我的urls.py:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
urlpatterns = [
# ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我上传的文件位于媒体根目录中,但是当我访问媒体 url [ http://127.0.0.1:8000/media/proof/img.pdf] 时,它 returns 未找到 HTTP 404。
请不要url硬编码。这不仅仅是不好的做法。
BASE_URL = 'http://127.0.0.1:8000'
你不能这样写。
你的解决方案,
settings.py
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
.......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
希望这能奏效。
我有一个 Django 项目。 为了设置我的媒体 url,我遵循了 django 文档 Django doc - Managing static files:
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings from django.conf.urls.static import static
urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我的 settings.py:
# ....
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = 'http://127.0.0.1:8000'
# ...
MEDIA_URL_REL = '/media/'
MEDIA_URL = BASE_URL + MEDIA_URL_REL
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
我的urls.py:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
urlpatterns = [
# ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我上传的文件位于媒体根目录中,但是当我访问媒体 url [ http://127.0.0.1:8000/media/proof/img.pdf] 时,它 returns 未找到 HTTP 404。
请不要url硬编码。这不仅仅是不好的做法。
BASE_URL = 'http://127.0.0.1:8000'
你不能这样写。
你的解决方案,
settings.py
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
.......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
希望这能奏效。