Django MEDIA_URL 和 MEDIA_ROOT

发布于 2024-10-29 09:02:36 字数 492 浏览 2 评论 0原文

我正在尝试通过 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 模式吗?

任何建议表示赞赏。

谢谢。

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.

My settings are as follows:

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

MEDIA_URL = '/media/'

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'

However, when I try to access the image at the following URL:

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

I get a 404 error.

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

Any advice appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

东风软 2024-11-05 09:02:36

更新 Django >= 1.7

根据 Django 2.1 文档:提供用户在开发过程中上传的文件

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 将处理确保这一点仅在调试模式下使用。


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>.*)

有了这个,您可以在 DEBUG = True(当您在本地计算机上运行时),但您可以在投入生产时让您的 Web 服务器配置提供静态媒体,并且 DEBUG = False

, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT}))

有了这个,您可以在 DEBUG = True(当您在本地计算机上运行时),但您可以在投入生产时让您的 Web 服务器配置提供静态媒体,并且 DEBUG = False

UPDATE for Django >= 1.7

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)

You no longer need if settings.DEBUG as Django will handle ensuring this is only used in Debug mode.


ORIGINAL answer for Django <= 1.6

Try putting this into your 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>.*)

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.views.static.serve', { 'document_root': settings.MEDIA_ROOT}))

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

度的依靠╰つ 2024-11-05 09:02:36

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

解决此问题的最佳且最简单的方法如下所示。

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)

Please read the official Django DOC carefully and you will find the most fit answer.

The best and easist way to solve this is like below.

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)
贩梦商人 2024-11-05 09:02:36

对于 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 -开发期间

For Django 1.9, you need to add the following code as per the documentation :

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)

For more info, you can refer here : https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development

木落 2024-11-05 09:02:36

这是我在 Django 2.0 中所做的。首先在 setting.py 中设置 MEDIA_ROOT 和 MEDIA_URL

MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
MEDIA_URL = '/media/'

TEMPLATE_CONTEXT_PROCESSORS 中启用 media context_processors

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            #here add your context Processors
            'django.template.context_processors.media',
        ],
    },
},
]

,然后通过添加您的 媒体上下文处理器已启用,现在每个 RequestContext 将包含一个变量 MEDIA_URL

现在您可以在 template_name.html 中访问它

<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>

Here What i did in Django 2.0. Set First MEDIA_ROOT an MEDIA_URL in setting.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
MEDIA_URL = '/media/'

Then Enable the media context_processors in TEMPLATE_CONTEXT_PROCESSORS by adding

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            #here add your context Processors
            'django.template.context_processors.media',
        ],
    },
},
]

Your media context processor is enabled, Now every RequestContext will contain a variable MEDIA_URL.

Now you can access this in your template_name.html

<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>
无语# 2024-11-05 09:02:36

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

是的。对于开发,只需将其添加到 URLconf 中即可轻松完成:

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
        (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
    )

但是,对于生产,您需要使用 Apache、lighttpd、nginx 或您首选的 Web 服务器来提供媒体服务。

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

Yes. For development, it's as easy as adding this to your URLconf:

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
        (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
    )

However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.

诗酒趁年少 2024-11-05 09:02:36

如果您使用的是 python 3.0+,请按如下所示配置您的项目

设置

STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

主 URL

from django.conf import settings
from django.conf.urls.static import static

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

If you'r using python 3.0+ then configure your project as below

Setting

STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

Main Urls

from django.conf import settings
from django.conf.urls.static import static

urlspatterns=[
........
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
流心雨 2024-11-05 09:02:36

(至少)对于 Django 1.8:

使用

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)

如果您如上所述 ,请确保在 urlpatterns = [] 中没有指向默认视图的“catch all”url 模式出现在该模式之前。由于 .append 会将添加的方案放在列表的末尾,因此当然只有在没有先前的 url 模式匹配的情况下才会对其进行测试。您可以通过使用类似这样的方法来避免这种情况,其中“catch all”url 模式添加在最后,独立于 if 语句:

if settings.DEBUG:
    urlpatterns.append(url(r'^media/(?P<path>.*)
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

如果您如上所述 ,请确保在 urlpatterns = [] 中没有指向默认视图的“catch all”url 模式出现在该模式之前。由于 .append 会将添加的方案放在列表的末尾,因此当然只有在没有先前的 url 模式匹配的情况下才会对其进行测试。您可以通过使用类似这样的方法来避免这种情况,其中“catch all”url 模式添加在最后,独立于 if 语句:


, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

urlpatterns.append(url(r'
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

如果您如上所述 ,请确保在 urlpatterns = [] 中没有指向默认视图的“catch all”url 模式出现在该模式之前。由于 .append 会将添加的方案放在列表的末尾,因此当然只有在没有先前的 url 模式匹配的情况下才会对其进行测试。您可以通过使用类似这样的方法来避免这种情况,其中“catch all”url 模式添加在最后,独立于 if 语句:

, 'views.home', name='home')), , 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

如果您如上所述 ,请确保在 urlpatterns = [] 中没有指向默认视图的“catch all”url 模式出现在该模式之前。由于 .append 会将添加的方案放在列表的末尾,因此当然只有在没有先前的 url 模式匹配的情况下才会对其进行测试。您可以通过使用类似这样的方法来避免这种情况,其中“catch all”url 模式添加在最后,独立于 if 语句:

(at least) for Django 1.8:

If you use

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

if settings.DEBUG:
    urlpatterns.append(url(r'^media/(?P<path>.*)
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:


, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

urlpatterns.append(url(r'
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

, 'views.home', name='home')), , 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

世界和平 2024-11-05 09:02:36

以下是我使用 Django 1.10 为 django-publications 应用程序交付 PDF 时必须进行的更改.6:

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)

以及修改@r-allela 在 settings.py 中提供的答案:

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',
            ],
         },
    },
]

Here are the changes I had to make to deliver PDFs for the django-publications app, using Django 1.10.6:

Used the same definitions for media directories as you, in settings.py:

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

MEDIA_URL = '/media/'

As provided by @thisisashwanipandey, in the project's main 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)

and a modification of the answer provided by @r-allela, in settings.py:

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',
            ],
         },
    },
]
会傲 2024-11-05 09:02:36

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

django.core.context_processors.media

TEMPLATE_CONTEXT_PROCESSORS 中的

Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }} won't work in your templates. To fix this,in your settings.py, make sure you add

django.core.context_processors.media

in your TEMPLATE_CONTEXT_PROCESSORS.

以为你会在 2024-11-05 09:02:36

按照上面提到的 =>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/'

Following the steps mentioned above for =>3.0 for Debug mode

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

And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.

Lastly make sure you set the following:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
淡淡離愁欲言轉身 2024-11-05 09:02:36

对于 Django 1.10 来说是这样的:

 if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This if for Django 1.10:

 if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
圈圈圆圆圈圈 2024-11-05 09:02:36

添加到 django 1.8 的 Micah Carrick 答案:

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

Adding to Micah Carrick answer for django 1.8:

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)
, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
呆橘 2024-11-05 09:02:36

这就是我在 Python 3.6 和 Django 1.11 中以 DEBUG = False 模式实现图像渲染所做的事情

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)
, serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)
, serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]
霞映澄塘 2024-11-05 09:02:36

在生产环境中,Django 不会自动加载媒体根目录,因此我们可以通过在 URL 模式后添加以下代码来解决该问题:

urlpatterns = [
       ''''
         your urls
       ''''
    ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)

如果您使用多个应用程序并且在主应用程序 url 上包含应用程序 url,只需添加以下代码主项目 URL 上的代码(配置)。

On production environment Django does not load the media root automatically so that we can overcome that issue by adding following codes right after URL patterns:

urlpatterns = [
       ''''
         your urls
       ''''
    ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)

If you are using more than one app and if you are including app urls on main app url, just add this code(configuration) on main project URL.

混吃等死 2024-11-05 09:02:36

将以下代码添加到“settings.py”以访问(打开或显示)上传的文件:

# "urls.py"

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Add this code below to "settings.py" to access(open or display)uploaded files:

# "urls.py"

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
柠檬色的秋千 2024-11-05 09:02:36

对于开发中的 Django 3.0+,您的主 urls.py 中应包含以下内容:

urlpatterns = [
   # rest of your url paths here..
]

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += (
        static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) +
        static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        )

For Django 3.0+ in development have the below in your main urls.py:

urlpatterns = [
   # rest of your url paths here..
]

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += (
        static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) +
        static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        )
悟红尘 2024-11-05 09:02:36

settings.py 中添加此代码

urlpatterns = [ 

....

....


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

Add this code in settings.py

urlpatterns = [ 

....

....


]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文