I have accented characters in my settings.py that I access in a view using getattr(settings, 'MY_CONSTANT_NAME', []) but the getattr() call return broken characters (for example, "ô" become: "\xc3\xb4").
here is the code in 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)
What I have done so far to try to solve the problem:
- I put # -- coding: utf-8 -- as the first line of my settings.py and my views.py
- I put u'ô' or unicode('ô') in front of special characters in settings.py
- I put DEFAULT_CHARSET = 'utf-8' in settings.py
- I try all possible combination of .decode('utf-8'), .encode('utf-8'), .decode('iso-8859-1'), .encode('iso-8859-1') on the special characters in settings.py or in the views.py...
Nothing solve the problem.
Any suggestion to solve this problem?
Thank you
Etienne
I assume you're seeing these
\xc3\xb4
strings in your browser.. Have you tried editing your template file to define the proper charset in the HTML header?Edit after your first comment in this answer:
I suspect
getattr
will not work with other thanascii
encoding. Do you think something like the following will not do what you want?Edit after last comments:
I think now I understand your problem. You don't like the fact that the JSON returned by the view is ASCII-only. I recommend you to use
dumps
function provided by thejson
module bundled with Python. Here's an example:The
CONSTANT_TUPLE
in the example is just a copy ofDATABASES
in mysettings.py
.The important bit here is
ensure_ascii=False
. Could you try it? Is that what you want?