0

I am using Django Restframework 3.3.3, and I am trying to use the generic views, but I was hoping to overwrite the serializer validation error message. I got the following code, which got a "name field cannot be blank" when the name field is not given.

class PositionList(generics.ListCreateAPIView):
    """Get the Position list, or add another Position only when you are admin"""
    renderer_classes = ((BrowsableAPIRenderer, JSONRenderer))        
    permission_classes = (IsAuthenticatedOrReadOnly, IsAdminOrReadOnly,)
    queryset = Position.objects.filter()
    serializer_class = PositionSerializer

My question is: is there a way to customize the error messages. The following methods dose not work for me: (1). Overwrite the init method in the serializer class:

 def __init__(self, *args, **kwargs):
    super(UserSerializer, self).__init__(*args, **kwargs)
    self.fields['name'].error_messages['required'] = 'My custom required msg'

(2). Give the error message in the serializer class:

class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Position
        fields = ('id', 'name', 'description')
        extra_kwargs = {"name": {"required": _("Customized message goes here")}}

Any advises are welcomed, thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
shady
  • 455
  • 1
  • 7
  • 18

2 Answers2

1

You almost did it right with serializer, you just forgot to put it inside error_messages

from django.utils.translation import ugettext_lazy as _

class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'name', 'description')
        extra_kwargs = {"name": {"error_messages": {"blank": _("Customized message goes here")}}}

Also you can try setting this message in model. Using blank

class MyModel(models.Model):
    name = models.CharField(..., error_messages={'blank': _("Customized message goes here")})
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
0

You can go as in your example 1, but instead of "required" use keyword "blank":

def __init__(self, *args, **kwargs):
    super(PositionSerializer, self).__init__(*args, **kwargs)
    self.fields['name'].error_messages['blank'] = 'My custom required msg'
milorad.kukic
  • 506
  • 4
  • 11
  • No luck, It is not working. I am using the `generic.ListCreateAPIView`. – shady Nov 25 '16 at 09:06
  • In serializer __init__ method make sure that, when you call super, you call with your class... For example, if your serializer is PositionSerializer, call it as: super(PositionSerializer, self),..... I'll edit example in my answer to match serializer name – milorad.kukic Nov 25 '16 at 11:56