django生产环境配置static,DEBUG=False

时间:2022-01-20 22:03:44 类型:python
字号:    

  1.首先setttings.py里面设置

STATIC_ROOT = os.path.join(BASE_DIR , "mystatic/static") ## 新增行
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

  2.执行python manage.py collectstatic收集静态文件, 把各个模块下的static下的文件拷贝到STATIC_ROOT指定的目录下

  3.在urls.py里面添加路由映射

from django.urls import path,include,re_path
from home import index
from django.conf import settings
import os



urlpatterns = [
    #path('admin/', admin.site.urls),
    path("",index.index),
    path('test/', include("test.urls")),
    path('yt/', include('zz.urls')),
    path('ueditor/',include('DjangoUeditor.urls'))
]

if not settings.DEBUG:
    from django.views import static
    urlpatterns += [re_path(r'^static/(?P<path>.*)$', static.serve,
      {'document_root': settings.STATIC_ROOT}, name='static')]
    urlpatterns += [re_path(r'^media/(?P<path>.*)$', static.serve,
                            {'document_root': settings.MEDIA_ROOT}, name='media')]

if settings.DEBUG:
    from django.conf.urls.static import static
    media_root = os.path.join(settings.BASE_DIR,settings.MEDIA_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root = media_root)
    #映射 /media   到statics/media目录


<