We use the JSONField
from django.contrib.postgres.fields
a lot in our
models. Everything works fine, except when you look at the data in Django's
admin, non-ascii characters are escaped. Eg. it displays M\\u00f6hringen
instead of Möhringen
(a district of
Stuttgart).
You can type in Möhringen
, press save and everything works as expected. It's
a pure visual issue. In one of our projects this was too annoying, so we fixed
it:
import json
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.forms.jsonb import (
InvalidJSONInput,
JSONField as JSONFormField,
)
class UTF8JSONFormField(JSONFormField):
def prepare_value(self, value):
if isinstance(value, InvalidJSONInput):
return value
return json.dumps(value, ensure_ascii=False)
class UTF8JSONField(JSONField):
"""JSONField for postgres databases.
Displays UTF-8 characters directly in the admin, i.e. äöü instead of
unicode escape sequences.
"""
def formfield(self, **kwargs):
return super().formfield(**{
**{'form_class': UTF8JSONFormField},
**kwargs,
})
The ensure_ascii=False
is the part that actually fixes it. Just replace
JSONField
with UTF8JSONField
in all relevant models.
Tell us what you think about this. Is something unclear? Do you have questions or ideas? Leave your comments below.
comments powered by Disqus