Django自定义设置404和500,自定义后static静态文件无法加载问题解决
1、编辑settings.py文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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
1 2 3 4 5 6 7 8 | from 模块名称 import views urlpatterns = [ '''''' ] handler404 = views.page_found404 handler500 = views.page_error500 |
4、编辑views.py
1 2 3 4 5 6 7 | def page_found404(request): request_path = request.path return render(request, '404.html' , locals ()) def page_error500(request): return render(request, '500.html' , locals ()) |
5、settings.py 配置文件里面 DEBUG = True 改成 DEBUG = False 无法准确的访问 static 静态文件
出现问题原因是:开发django应用时默认设置为 DEBUG = True,django自动对静态文件进行路由;设置DEBUG = False后这一功能将会消失,此时静态文件就会出现加载失败的情况,想要让静态文件正常显示,需要进行新的相关静态文件进行设置
settings.py文件进行修改编辑
1 2 3 4 5 6 7 | STATIC_URL = '/static/' STATIC_ROOT = 'static' #添加新一行 STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static/' ) #进行修改 ] |
urls.py修改编辑
1 2 3 4 5 6 7 8 9 10 11 12 | 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' ), ] |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署