Django rest-framework api and unicode characters

I am using django-rest-framework to create api for my application. In my application, Greek letters are used as values ​​for its models. I created my views and used UnicodeJSONRenderer to return json result.

class ChapterViewSet(viewsets.ModelViewSet):
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer
    renderer_classes = (UnicodeJSONRenderer, )

      

Json is returned, but Greek letters are not recognized by the browser ("Ξ ΟΟΟΞΈΞΟΞ ·)) On the chrome dev console, although the response preview shows Greek letters as usual in the Network tab. How can I recognize Greek letters in the browser?

+3


source to share


3 answers


This is a browser issue.

UTF-8 is the default encoding for JSON content; Django Rest Framework encodes your JSON correctly to UTF-8, but your browser doesn't display it correctly.



Browsers will render it correctly if supplied charset=utf-8

with the HTTP Content-Type header. However, the spec defines another way to define encoding , so this should not be used. Django Rest Framework enforces this by not including it.

There is an open ticket for Chrome, but unfortunately nobody seems to care. It seems like other browsers have the same problem. See also this SO question .

+4


source


This is a really strange problem that I am facing; my first impression was that the Django REST Framework was supposed to set UTF-8 encoding in the header Content-Type

, but this has already been filed as issue # 2891 and there seems to be a lot of controversy about this.



The fix I used was to just set the UNICODE_JSON

value False

. This leads to larger answers, especially if your answer has a lot of unicode characters, for example, the horizontal ellipse becomes \u2026

in line rather than the equivalent 3-byte UTF-8 representation, but clients are less likely to be misunderstood.

+2


source


Which fixed for me (I need an accent because of the pt-BR)

Go to your settings.py file and include

REST_FRAMEWORK = {
    #this bit makes the magic.
    'DEFAULT_RENDERER_CLASSES': (
         #UnicodeJSONRenderer has an ensure_ascii = False attribute,
         #thus it will not escape characters.
        'rest_framework.renderers.UnicodeJSONRenderer',
         #You only need to keep this one if you're using the browsable API
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}
      

Run codeHide result


This way you don't have to include the renderer_classes serializer on every view you have.

Hope it gets fixed for you too!

0


source







All Articles