0
votes

I am still beginner in django.

When I save into database, I got this error.

'ascii' codec can't encode character u'\uff1f' in position 14: ordinal not in range(128)

I have seen similar question here though but I have tried and it is still not okay.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

I believe it happen in this data['english'].

Shall I change in views.py or serializer?

My view is

class DialogueView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):

        data = request.data
        serializer = DialogueSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=
                status.HTTP_400_BAD_REQUEST)
        else:
            owner = request.user
            t = Dialogue(owner=owner, english=data['english'])
            t.save()
            # request.data['id'] = t.pk # return id
            return Response(status=status.HTTP_201_CREATED)

My serializer is

class DialogueSerializer(serializers.ModelSerializer):

    sound_url = serializers.SerializerMethodField()

    class Meta:
        model = Dialogue
        fields = ('id','english','myanmar', 'sound_url') 

    def get_sound_url(self, dialogue):
        if not dialogue.sound:
            return None

        request = self.context.get('request')
        sound_url = dialogue.sound.url
        return request.build_absolute_uri(sound_url)
1
Which version of python? - Sardorbek Imomaliev
I am using python 2.7 - Khant Thu Linn
Do you have magic comment # coding: utf-8 on the first line of your serializer and view files? - Sardorbek Imomaliev
amm no. I don't have. - Khant Thu Linn
Add it. It may solve your problem. - Sardorbek Imomaliev

1 Answers

0
votes

It might be that the DB doesn't accept Unicode value as a string field.

To solve this, try two ways:

  1. Change DB config into using a unicode encoding. E.g. This post for mysql.

  2. Encode that unicode value before storing into DB. Try converting the value like this: val = data['English'] and store val to your model.