Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Accented characters in settings.py are broken when accessed in a view

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

like image 381
Etienne Desgagné Avatar asked Dec 03 '25 06:12

Etienne Desgagné


1 Answers

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?

like image 112
Diego Schulz Avatar answered Dec 06 '25 16:12

Diego Schulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!