AX Semantics Developer Blog
  • Home
  • Categories
  • Tags
  • Archives

Unescaped UTF-8 in Django's admin with JSONField

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
comments powered by Disqus

  • « Write-once fields with Django Rest Framework
  • Django and Postgres' jsonb field beyond the basics »

Published

Nov 10, 2016

Category

Techstack

Tags

  • django 3
  • python 8
  • AX Semantics Developer Blog - Technical stuff and learnings we had while developing the AX environment
  • Powered by Pelican. Theme: Elegant by Talha Mansoor