Django MEDIA_URL和MEDIA_ROOT [英] Django MEDIA_URL and MEDIA_ROOT

查看:851
本文介绍了Django MEDIA_URL和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参数设置为图像,文件已正确上载到目录中:

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错误。

我需要为上传的媒体设置特定的URLconf模式吗?

Do I need to setup specific URLconf patters for uploaded media?

任何建议赞赏。

谢谢。

推荐答案

进入您的 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}))

有了这个,您可以在$ code> DEBUG = True (当您在本地计算机上运行时),但您可以让您的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆