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:
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?
<head>
<meta name="description" content="example" />
<meta name="keywords" content="something" />
<meta name="author" content="Etienne" />
<meta charset="UTF-8" /> <!-- <---- This line -->
</head>
Edit after your first comment in this answer:
I suspect getattr will not work with other than ascii encoding. Do you think something like the following will not do what you want?
from django.conf import settings
def getValueFromSetting(request):
myConstantValue = settings.MY_CONSTANT_NAME
# check myConstantValue here
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 the json module bundled with Python. Here's an example:
# -*- 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
The CONSTANT_TUPLE in the example is just a copy of DATABASES in my settings.py.
The important bit here is ensure_ascii=False. Could you try it? Is that what you want?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With