问题
I have a django project. In order to set up my media url, I followed the django doc 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)
my 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/')
my 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)
My uploaded files are found in media root, but when I access media url [ http://127.0.0.1:8000/media/proof/img.pdf]for it, it returns HTTP 404 NOT FOUND.
回答1:
Please don't make any url with hard coded. This is more than bad practice.
BASE_URL = 'http://127.0.0.1:8000'
You can't write like that.
Your solution,
settings.py
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
.......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hope this works.
来源:https://stackoverflow.com/questions/42200568/django-media-url-returns-404-not-found