【问题标题】:django's setting.py can't read utf-8 charactersdjango 的 setting.py 无法读取 utf-8 字符
【发布时间】:2018-06-27 16:40:19
【问题描述】:

我试图为我的MEDIA_ROOT 赋予一个包含带重音符号的单词的值,但 django 不接受它。 我尝试了 unicode(utf-8) 并对其进行编码,但没有得到肯定的结果

我得到的错误是:SyntaxError: Non-ASCII character '\xc3' in file 我该怎么做才能使设置接受重音符号(ó,á,é,í,ú)

SyntaxError: Non-ASCII character '\xc3' in file C:\Users\Meccha\Documents\django\project\settings.py on line 160, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

在第 160 行我有:MEDIA_ROOT = os.path.join(u'D:', u'INVESTIGACIÓN._P')

【问题讨论】:

  • 你在运行 Python-2.x 吗?
  • 是的,python 2.7 和 django 1.11
  • 那么你需要在它前面加上一个u,所以u'foo/bar/qux' insteaf of 'foo/bar/qux'
  • 我得到同样的错误SyntaxError: Non-ASCII character '\xc3' in file settings.py but no encoding declared
  • 在顶部添加# -*- coding: utf-8 -*-

标签: django django-settings


【解决方案1】:

中,strunicode 之间有一个目的地。 strASCII 字符串,因此它们只能包含 ASCII 字符。另一方面,unicode 字符串可以包含所有 unicode 字符。

您可以使用u 前缀定义一个unicode 字符串,这样就可以编写像u'\xf3' 这样的unicode 字符来编写一个包含Ã 字符的unicode 字符串。

但是,如果您也想编写 unicode 字符串,则需要在文件头中指定文件的编码。那么 settings.py 文件看起来像:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os

# ...
# (some other settings)
# ...

MEDIA_ROOT = os.path.join('D:', u' INVESTIGACIÓN_P')

所以上面部分指定了编码,后面有一个u前缀,将字符串标记为unicode字符串。

【讨论】:

  • 我遇到了和以前一样的问题
  • @Mecha:请发布完整的回溯。
  • @Mecha:您好像忘记声明编码了(请参阅顶部的粗体部分!)
  • 我已经添加了
  • @Mecha:如果你添加一个from __future__ import unicode_literals呢?
猜你喜欢
  • 1970-01-01
  • 2017-08-29
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 2015-05-20
  • 1970-01-01
相关资源
最近更新 更多