在 Django 中,在 python 任何地方进行媒体部署的正确设置是什么

In django, what is correct setup for media deployment on python anywhere

我正在尝试在 python 上的任何地方部署我的 django 应用程序,但我认为 media_urls 或 media_root 可能设置不正确。我还花时间试图弄清楚如何在 django 上打印所有有效的 url,但在这个 link 上对我没有任何作用。 Django : How can I see a list of urlpatterns?.

我收到了 "ModuleNotFoundError: No module named 'django.core.urlresolvers'"

from .base import *

DEBUG = False

ALLOWED_HOSTS = ["*"]

MEDIA_ROOT = os.path.join(BASE_DIR, "images")
MEDIA_URL = '/snapcapsule/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

回答

大多数时候,我在本地使用 django 服务静态和媒体,在服务器使用 nginx。

本地:

# at the end of urls.py
if settings.DEBUG:
    # debug toolbar
    import debug_toolbar

    urlpatterns.insert(0, path("__debug__/", include(debug_toolbar.urls)))

    # static and media
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns

    urlpatterns.extend(
        staticfiles_urlpatterns()
        + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    )

在服务器中:

# nginx.conf
server {
    ...
    location /static/ {
        alias /path/to/project/static_collection/;
    }

    location /media/ {
        alias /path/to/project/media/;
    }
}

您的图像静态文件映射位于 /images,但您正在从 /snapcapsule/images 访问图像。更改您的 media_url 或您的静态文件映射,使它们匹配。