要明白,在开发django的时候,如果设置了 DEBUG = True,django便会自动帮我们对静态文件进行路由;
但是当我们设置DEBUG = False后,这一功能便没有了,因此静态文件就会出现加载失败的情况,想要让静态文件正常显示,就需要手动配置静态文件服务了。
在views中
from django.shortcuts import render
def bad_request(request, exception, template_name='400.html'):
return render(request, template_name)
def permission_denied(request, exception, template_name='403.html'):
return render(request, template_name)
def page_not_found(request, exception, template_name='404.html'):
return render(request, template_name)
# 注意这里没有 exception 参数
def server_error(request, template_name='500.html'):
return render(request, template_name)
在settings文件中配置:
# DEBUG = True
#
# ALLOWED_HOSTS = []
DEBUG = False # 开发环境下为True,此时我们改为False
ALLOWED_HOSTS = ['*'] # 或者 ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
第一种说法 这种会报错,重复包含,有悖于唯一性
STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = (os.path.join(BASE_DIR, 'static').replace('\\','/'))
第二种说法
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
这一部很关键,一定要把东西都给手机过来,尤其是静态的,只要这样才能自由访问
python manage.py collectstatic
也可以在控制台执行如下命令,它会在根目录下生成static文件,里边存储的是xadmin的样式文件:
tools---run manage.py task collectstatic
在urls文件中配置:
from django.conf.urls import url
from . import rviews
handler400 = rviews.bad_request
handler403 = rviews.permission_denied
handler404 = rviews.page_not_found
handler500 = rviews.server_error
首先,导入:
from django.views.static import serve
然后,在 urlpatterns 中加入:
url(r'^static/(?P<path>.*)$',serve,{'document_root': settings.STATIC_ROOT}), django1
re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), django2
re_path('static/(?P<path>.*)', serve, {'document_root':STATIC_ROOT}),
【问题原因】:django的生产环境不同开发环境,在生产环境下(DEBUG=False),django.contrib.staticfiles 是不起任何作用的,也就说 django.contrib.staticfiles 只对开发环境(DEBUG=True)开启。所以会导致xadmin样式丢失现象。
Debug True的时候使用这个
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
|