Django MEDIA_URL 和 MEDIA_ROOT [英] Django MEDIA_URL and MEDIA_ROOT
问题描述
我正在尝试通过 Django 管理员上传图像,然后在前端页面中或仅通过 URL 查看该图像.
I'm trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.
注意这一切都在我的本地机器上.
Note this is all on my local machine.
我的设置如下:
MEDIA_ROOT = '/home/dan/mysite/media/'
MEDIA_URL = '/media/'
我已经将upload_to参数设置为'images'并且文件已正确上传到目录:
I have set the upload_to parameter to 'images' and the file has been correctly uploaded to the directory:
'/home/dan/mysite/media/images/myimage.png'
但是,当我尝试通过以下 URL 访问图像时:
However, when I try to access the image at the following URL:
http://127.0.0.1:8000/media/images/myimage.png
我收到 404 错误.
I get a 404 error.
我需要为上传的媒体设置特定的 URLconf 模式吗?
Do I need to setup specific URLconf patters for uploaded media?
感谢任何建议.
谢谢.
推荐答案
UPDATE for Django >= 1.7
每个 Django 2.1 文档:提供用户在开发过程中上传的文件
Per Django 2.1 documentation: Serving files uploaded by a user during development
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
您不再需要 if settings.DEBUG
因为 Django 将处理确保它仅在调试模式下使用.
You no longer need if settings.DEBUG
as Django will handle ensuring this is only used in Debug mode.
Django <= 1.6 的原始答案
尝试将其放入您的 urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
有了这个,您可以在 DEBUG = True
时从 Django 提供静态媒体(当您在本地计算机上运行时),但是您可以让您的 Web 服务器配置在您进入生产和 DEBUG = False
With this you can serve the static media from Django when DEBUG = True
(when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False
这篇关于Django MEDIA_URL 和 MEDIA_ROOT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!