如果 MEDIA_URL 在 STATIC_URL 之内,runserver 无法提供媒体服务

runserver can't serve media if MEDIA_URL is within STATIC_URL

我的配置如下:

STATIC_URL = '/static/'
MEDIA_URL = '/static/media/'

自从我将 django 2.1 升级到 2.2 后,我得到:

"runserver can't serve media if MEDIA_URL is within STATIC_URL."
django.core.exceptions.ImproperlyConfigured: runserver can't serve media if MEDIA_URL is within STATIC_URL.

我理解错误。我的问题是"why not"?您有充分的理由希望媒体作为静态的子目录。

此外,在 2.2 发行说明中零提及此重大更改:https://docs.djangoproject.com/en/3.0/releases/2.2/

此警告已响应此票证 #29570: Add check that MEDIA_URL is not inside STATIC_URL.

也引用 #15199: Allow MEDIA_ROOT inside STATIC_ROOT

After further IRC discussion with jezdez, closing this wontfix. Supporting a configuration with MEDIA_ROOT inside STATIC_ROOT introduces a number of additional complexities and couplings between staticfiles and the MEDIA_* settings, which we are trying to avoid, and it's not clear what meaningful benefits it buys us. The main mentioned benefit was to only require one alias on the front-end webserver: that seems minor, since an alias is e.g. just one line in an nginx conf file. In any case, the same result can be achieved by putting MEDIA_ROOT and STATIC_ROOT side by side in a parent directory, and aliasing the front-end webserver to that parent directory.

基本上,您可以:

STATIC_URL = '/static/static/'
MEDIA_URL = '/static/media/'

由于这是在开发环境中进行的检查,您可以

STATIC_URL = '/static/'
MEDIA_URL = 'static/media/'
if DEBUG:
    MEDIA_URL = 'media/'