今天用Django搭建一个环境,在访问后台的时候感觉有点怪:
感觉后台页面的样式似乎没有被加载进来,于是单独打开某个样式结果浏览器提示:
A server error occurred. Please contact the administrator.
命令行:
Traceback (most recent call last):
File "D:Python27libwsgirefhandlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "D:Python27libsite-packagesdjangocontribstaticfileshandlers.py", line 68, in __call__
return super(StaticFilesHandler, self).__call__(environ, start_response)
File "D:Python27libsite-packagesdjangocorehandlerswsgi.py", line 206, in __call__
response = self.get_response(request)
File "D:Python27libsite-packagesdjangocontribstaticfileshandlers.py", line 58, in get_response
return self.serve(request)
File "D:Python27libsite-packagesdjangocontribstaticfileshandlers.py", line 51, in serve
return serve(request, self.file_path(request.path), insecure=True)
File "D:Python27libsite-packagesdjangocontribstaticfilesviews.py", line 41, in serve
return static.serve(request, path, document_root=document_root, **kwargs)
File "D:Python27libsite-packagesdjangoviewsstatic.py", line 61, in serve
content_type, encoding = mimetypes.guess_type(fullpath)
File "D:Python27libmimetypes.py", line 297, in guess_type
init()
File "D:Python27libmimetypes.py", line 358, in init
db.read_windows_registry()
File "D:Python27libmimetypes.py", line 258, in read_windows_registry
for subkeyname in enum_types(hkcr):
File "D:Python27libmimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
File "D:Python27libencodingsutf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 1: invalid start byte
一看就知道就知道又是蛋疼的Python编码问题了,每次写Python项目,总要被编码问题折腾几下,这次也不例外。结果网上一搜,也没搜出解决方法,倒是相关错误有人给出页面顶部加上编码设置:
#encoding:utf8
这有点要命,django项目那么多文件怎么加?应该是配置里有,于是找到了相关信息并在settings.py里添加:
DEFAULT_CHARSET = 'utf-8'
FILE_CHARSET = 'utf-8'
结果还是没有解决问题,又看到有人建议用g www.111cn.net b18030,只好把上面那两句改成
DEFAULT_CHARSET = 'gb18030'
FILE_CHARSET = 'gb18030'
问题仍旧没有解决,最后摸索了两个小时快接近崩溃边缘时,偶然我的一个设置居然把这痛苦编码问题给解决了,在manage.py添加:
reload = reload(sys)
sys.setdefaultencoding('gb18030')
问题解决,打开css静态文件也正常响应内容了