Django自定义设置404和500,自定义后static静态文件无法加载问题解决

1、编辑settings.py文件

1)DEBUG = True 改成 DEBUG = False
2)对TEMPLATES编辑修改 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #添加‘DIRS’这行 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]

2、在templates目录下404.html和500.html文件

1)建立404.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404访问失败</title>
</head>
<body>
<h1 style="text-align: center">404 访问失败</h1>
<hr>
<p style="text-align: center">{{ request_path }}路径页面不存在</p>
</body>
</html>

2)建立500.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500错误</title>
</head>
<body>
<h1 style="text-align: center">访问服务器500错误</h1>
</body>
</html>

3、编辑urls.py

from 模块名称 import views

urlpatterns = [
   ''''''
]

handler404 = views.page_found404
handler500 = views.page_error500

4、编辑views.py

def page_found404(request, exception=None):
request_path = request.path
return render(request, '404.html', {"request_path": request_path})


def page_error500(request):
return render(request, '500.html')

5、settings.py 配置文件里面 DEBUG = True 改成 DEBUG = False 无法准确的访问 static 静态文件

出现问题原因是:开发django应用时默认设置为 DEBUG = True,django自动对静态文件进行路由;设置DEBUG = False后这一功能将会消失,此时静态文件就会出现加载失败的情况,想要让静态文件正常显示,需要进行新的相关静态文件进行设置

 settings.py文件进行修改编辑

STATIC_URL = '/static/'

STATIC_ROOT = 'static'  #添加新一行

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '/static/')  #进行修改
]



注:如果提示
WARNINGS:
?: (staticfiles.W004) The directory '/static/' in the STATICFILES_DIRS setting does not exist.

把下面内容注释
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '/static/')  #进行修改
]

urls.py修改编辑

1、导入下面三行
from django.views import static
from django.conf import settings
from django.conf.urls import url

2、
urlpatterns = [
    path('admin/', admin.site.urls),
    #添加下面内容
    url(r'^static/(?P<path>.*)$', static.serve,
        {'document_root': settings.STATIC_ROOT}, name='static'),
]


3、如果django 不在支持url使用repath

from django.contrib import admin
from django.urls import path, re_path, include
from django.views import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^static/(?P<path>.*)$', static.serve,
        {'document_root': settings.STATIC_ROOT}, name='static'),
]

  

 

posted @ 2022-01-27 16:47  点点滴滴的努力  阅读(444)  评论(0)    收藏  举报