serializers validationerror django

Solutions on MaxInterview for serializers validationerror django by the best coders in the world

showing results for - "serializers validationerror django"
César
23 Feb 2018
1class HighScoreSerializer(serializers.BaseSerializer):
2    def to_internal_value(self, data):
3        score = data.get('score')
4        player_name = data.get('player_name')
5
6        # Perform the data validation.
7        if not score:
8            raise serializers.ValidationError({
9                'score': 'This field is required.'
10            })
11        if not player_name:
12            raise serializers.ValidationError({
13                'player_name': 'This field is required.'
14            })
15        if len(player_name) > 10:
16            raise serializers.ValidationError({
17                'player_name': 'May not be more than 10 characters.'
18            })
19
20        # Return the validated values. This will be available as
21        # the `.validated_data` property.
22        return {
23            'score': int(score),
24            'player_name': player_name
25        }
26
27    def to_representation(self, instance):
28        return {
29            'score': instance.score,
30            'player_name': instance.player_name
31        }
32
33    def create(self, validated_data):
34        return HighScore.objects.create(**validated_data)