Django静态文件加载异常求助:路径不存在、文件未加载
我的Django应用存在静态文件加载不稳定的问题:有时页面能正常渲染,但频繁出现部分静态文件加载失败的情况,导致页面显示异常。目前已被这个问题困扰一个月,可提供文件访问权限或更多细节信息协助排查。
环境与配置信息
开发环境使用Whitenoise提供静态文件服务,核心配置如下:
STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
已做排查动作
- 确认目标文件
logo-removebg.png存在,模板中调用语法正确:src="{% static 'main/img/logo-removebg.png' %}" - 执行过
collectstatic命令,问题未解决
错误日志片段
Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/views/static.py", line 40, in serve raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) django.http.response.Http404: “/home/srv52965/main/staticfiles/main/img/logo-removebg.png” does not exist During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 880, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 890, in _resolve_lookup current = getattr(current, bit) AttributeError: 'URLResolver' object has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 903, in _resolve_lookup raise VariableDoesNotExist( django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <module 'allauth.urls' from '/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/allauth/urls.py'> (None:None) 'account/' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/alt/python38/lib64/python3.8/logging/__init__.py", line 1088, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 602: ordinal not in range(128) Call stack: File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/whitenoise/base.py", line 81, in __call__
排查与解决建议
验证静态文件实际路径与权限
登录服务器检查/home/srv52965/main/staticfiles/main/img/logo-removebg.png是否真实存在(Linux环境路径区分大小写),同时确认文件权限设置为644、目录权限755,确保Web进程有读取权限。校正Whitenoise中间件顺序
在settings.py中,Whitenoise中间件必须放在SecurityMiddleware之后、其他中间件之前,配置示例:MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 其余中间件... ]临时切换静态文件存储模式
暂时将STATICFILES_STORAGE改为whitenoise.storage.CompressedStaticFilesStorage(移除Manifest后缀),重新执行collectstatic后观察问题是否消失。Manifest模式生成的哈希文件名若出现缓存或同步异常,可能导致文件找不到。修复模板变量查找错误
日志中出现的VariableDoesNotExist错误,说明某模板错误地尝试从URLResolver对象中获取name变量,虽和静态文件问题无关,但会干扰日志排查。检查allauth相关模板或自定义auth模板,修正错误的变量调用。解决日志编码问题
服务器日志用ASCII编码导致Unicode字符无法写入,可在settings.py中配置日志编码为UTF-8:LOGGING = { # 其他配置... 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'encoding': 'utf-8', }, }, }清除静态文件缓存
若使用反向代理,清除代理缓存后测试;同时重启Django应用进程,清除Whitenoise内存缓存。
内容的提问来源于stack exchange,提问作者Kamil

