Python 找不到页面 404 Django 媒体文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36280056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Page not found 404 Django media files
提问by madhu131313
I am able to upload the files to media folder( '/peaceroot/www/media/'
) that I have set up in settings.py
as below
我可以将文件上传到'/peaceroot/www/media/'
我设置的媒体文件夹(),settings.py
如下所示
MEDIA_ROOT = '/peaceroot/www/media/'
MEDIA_URL = '/media/'
But through admin I tried to access the uploaded image file
但是通过管理员我试图访问上传的图像文件
http://localhost:8000/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg
http://localhost:8000/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg
then I am getting 404 error.
然后我收到 404 错误。
The file exists at peaceroot/www/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg
该文件存在于 peaceroot/www/media/items/1a39246c-4160-4cb2-a842-12a1ffd72b3b.jpg
回答by v1k45
Add media url entry in your project urlpatterns:
在您的项目 urlpatterns 中添加媒体 url 条目:
from django.conf.urls.static import static
from django.conf import settings
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
回答by Kjjassy
The better way for MEDIA_ROOT is,
MEDIA_ROOT 的更好方法是,
try to make media path dynamic will be easy when you shift your project.
当您转移项目时,尝试使媒体路径动态化会很容易。
Settings.py
设置.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\', '/')
MEDIA_URL = '/media/'
urls.py
网址.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)
Look at this
看这个
回答by Seyi Shoboyejo
Just to add: in case the other answers do not work for you, try putting the static url before the other ones. Like so:
补充一点:如果其他答案对您不起作用,请尝试将静态 url 放在其他答案之前。像这样:
urlpatterns = static(...) + [...]
What may be happening is that some of your patterns in the list prevent the request from reaching the static handlers. So putting the static handlers first solves this. Worked for me.
可能发生的情况是列表中的某些模式阻止请求到达静态处理程序。所以首先放置静态处理程序可以解决这个问题。为我工作。