Django:settings.py中的重音字符在视图中访问时会断开

Django:settings.py中的重音字符在视图中访问时会断开,django,unicode,encoding,character-encoding,Django,Unicode,Encoding,Character Encoding,我在我的settings.py中有重音字符,我使用getattr(settings,'my_CONSTANT_NAME',[])在视图中访问这些字符,但是getattr()调用返回的是断字符(例如,“ô”变为“\xc3\xb4”) 以下是view.py中的代码: from django.conf import settings def getValueFromSetting(request): mimetype = 'application/json'

我在我的settings.py中有重音字符,我使用getattr(settings,'my_CONSTANT_NAME',[])在视图中访问这些字符,但是getattr()调用返回的是断字符(例如,“ô”变为“\xc3\xb4”)

以下是view.py中的代码:

    from django.conf import settings

    def getValueFromSetting(request):
        mimetype = 'application/json' 
        charset=utf-8' datasources = getattr(settings, 'MY_CONSTANT_NAME', []) 
        config= '{' 
        config+= '"datasources": ' + str(datasources).replace("'", '"') 
        config+= '}'

        return HttpResponse(config,mimetype)                      
到目前为止,我为解决这个问题所做的努力:

  • 我将#--coding:utf-8--作为我的settings.py和我的views.py的第一行
  • 我在settings.py中的特殊字符前面加上了uô或unicode(ô)
  • 我在settings.py中放置了默认的字符集='utf-8'
  • 我尝试对settings.py或views.py中的特殊字符使用.decode('utf-8')、.encode('utf-8')、.decode('iso-8859-1')、.encode('iso-8859-1')的所有可能组合
什么也解决不了问题

有什么解决这个问题的建议吗

多谢各位


Etienne

我假设您在浏览器中看到了这些
\xc3\xb4
字符串。。您是否尝试过编辑模板文件以在HTML标头中定义正确的字符集

<head>
  <meta name="description" content="example" />
  <meta name="keywords" content="something" />
  <meta name="author" content="Etienne" />
  <meta charset="UTF-8" />      <!--  <---- This line -->
</head>
在最后评论后编辑:

我想我现在明白你的问题了。您不喜欢视图返回的JSON仅为ASCII。我建议您使用Python附带的
json
模块提供的
dumps
函数。下面是一个例子:

# -*- coding: utf-8 -*-
# other required imports here
import json

def dumpjson(request):
   response = HttpResponse(json.dumps(settings.CONSTANT_TUPLE, encoding='utf-8', ensure_ascii=False), content_type='application/json')

   return response
示例中的
常量\u元组
只是my
settings.py中
数据库
的一个副本


这里重要的一点是
确保ascii=False
。你能试试吗?这就是您想要的吗?

在发送到浏览器之前,我看到了这些字符串。。。我在调试时(在Aptana Studio中)直接在我的视图中看到了它。。。我在我的浏览器中也看到了同样的行为,甚至在网页中我只是尝试了一下,我在使用myConstantValue=settings.my_CONSTANT_NAME而不是调用getattr时遇到了同样的字符集问题……您能再显示一点代码吗?您在该视图中使用
myConstantValue
做什么?模板呢?我的目标是从settings.py获取这个常量,并将其以JSON格式返回到Javascript的Ajax调用中。常量包含一个词汇列表。如果您更新原始问题中的代码块,将更容易阅读。那么您到底在哪里看到这个“损坏”的输出?事实上,我觉得这完全正确,但没关系。如何输出该值?
from django.conf import settings

def getValueFromSetting(request):
    myConstantValue = settings.MY_CONSTANT_NAME
    # check myConstantValue here