我试图通过Django管理员上传一个图像,然后在前端的页面或只是通过URL查看该图像。

注意,这些都在我的本地机器上。

我的设置如下:

MEDIA_ROOT = '/home/dan/mysite/media/'

MEDIA_URL = '/media/'

我已经将upload_to参数设置为'images',文件已经正确上传到目录:

'/home/dan/mysite/media/images/myimage.png'

然而,当我试图访问下面的URL图像:

http://127.0.0.1:8000/media/images/myimage.png

我得到一个404错误。

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

任何建议都很感激。

谢谢。


当前回答

对于调试模式,执行上述步骤=>3.0

urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这也是我发现的部分,上面的静态URL只在我的主项目urls.py文件中工作。我第一次尝试添加到我的应用程序,并想知道为什么我不能看到图像。

最后确保你设置了以下内容:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

其他回答

你的设置没问题。一些web服务器需要特别指定媒体和静态文件夹文件。例如,在pythonanywhere.com中,你必须去“Web”部分,并添加媒体文件夹和静态文件夹的url。例如:

  URL                     Directory                
/static/            /home/Saidmamad/discoverthepamirs/static     
/accounts/static/   /home/Saidmamad/discoverthepamirs/accounts/static    
/media/            /home/Saidmamad/discoverthepamirs/discoverthepamirs/media    

我知道已经很晚了,但只是为了帮助那些因为同样的问题访问这个链接的人;)

在设置完所有URLconf模式后,您可能面临的另一个问题是变量{{MEDIA_URL}}在模板中不起作用。要解决这个问题,在settings.py中,确保添加

django.core.context_processors.media

在TEMPLATE_CONTEXT_PROCESSORS中。

请仔细阅读Django官方文档,你会找到最合适的答案。

解决这个问题的最好和最简单的方法如下。

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)

对于Django 1.9,你需要根据文档添加以下代码:

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)

欲了解更多信息,请访问:https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development

下面是我使用Django 1.10.6为Django -publications应用程序交付pdf文件所做的更改:

在settings.py中使用与您相同的媒体目录定义:

MEDIA_ROOT = '/home/user/mysite/media/'

MEDIA_URL = '/media/'

由@thisisashwanipandey提供,在项目的主要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中,对@r-allela提供的答案进行了修改:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # ... the rest of your context_processors goes here ...
                'django.template.context_processors.media',
            ],
         },
    },
]