shady shady - 1 year ago 103
Python Question

overwrite django restframework CreateModelMixin serializer error message

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 advanced.

Answer Source

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")})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download