0

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)
Community
  • 1
  • 1
Khant Thu Linn
  • 5,905
  • 7
  • 52
  • 120

1 Answers1

0

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.

SolessChong
  • 3,370
  • 8
  • 40
  • 67
  • Thanks. I will read through about 1. Can you please elaborate more on 2? It is because I have read through some link to encode and it is not okay. I am not sure whether it happen in view or serializer also. – Khant Thu Linn Oct 10 '16 at 15:21
  • You could conver the encoding in model's `save` function as is described in [this question](http://stackoverflow.com/questions/4269605/django-override-save-for-model) – SolessChong Oct 10 '16 at 15:28