2

I am using ModelViewSet and TemplateHTMLRenderer to use the form and process 'post' method. When I tried render a field error, the error rendered [u'This field may not be blank.']. How can I make it render the simple message 'This...'?

in html,

<form action="." method="post" id="myform">
     <input name="first_name" type="text">
     <ul> {{ errors.first_name }}</ul>
</form>

in views.py,

class UserViewSet(viewsets.ModelViewSet):
   queryset = User.objects.all()
   serializer_class = UserSerializer
   renderer_classes = (renderers.JSONRenderer, renderers.TemplateHTMLRenderer)
   template_name = 'account.html'

   def list(self, request, *args, **kwargs):
     response = super(AccountViewSet, self).list(request, *args, **kwargs)
     if request.accepted_renderer.format == 'html':
        return Response({'data': response.data}, template_name=self.template_name)
     return response

   def create(self, request):
     serializer = self.serializer_class(data=request.data)
     if serializer.is_valid():
        User.objects.create_user(**serializer.validated_data)
        return Response(serializer.validated_data)
     return Response({'errors': serializer.errors})

And I overrode rest framework's default required error message in serializer.py, but it seemed it ignored the customized required error message and showed the default required error message such as 'This field may not be blank..'.

in serializer.py,

class UserSerializer(serializers.ModelSerializer):
     first_name = serializers.RegexField(regex=r'^[a-zA-Z -.\'\_]+$',       
            required=True,
            error_messages={'required': _('Please enter your first name.'),
                            'invalid': _('Please enter a valid name.')})

What's wrong here?

user2307087
  • 423
  • 11
  • 25
  • http://stackoverflow.com/questions/26943985/custom-error-messages-in-django-rest-framework-serializer – chandu Jun 03 '15 at 08:43

1 Answers1

1

The errors are not coming because DRF is running field validations initially. If those validations fail, the default errors are shown.

As per the source code, the default error messages are stored in default_error_messages dictionary. Following are some code snippets:

Field:

class Field(object):   
    default_error_messages = {
        'required': _('This field is required.'),
        'null': _('This field may not be null.')
    }

CharField:

class CharField(Field):
    default_error_messages = {
        'blank': _('This field may not be blank.'),
        'max_length': _('Ensure this field has no more than {max_length} characters.'),
        'min_length': _('Ensure this field has at least {min_length} characters.')
    }

RegexField:

class RegexField(CharField):
    default_error_messages = {
        'invalid': _('This value does not match the required pattern.')
    }

So, what you can do is you can override the default_error_messages value by overriding the serializer's __init__ method and provide your custom error message.

class UserSerializer(serializers.ModelSerializer):
     first_name = serializers.RegexField(regex=r'^[a-zA-Z -.\'\_]+$',       
            required=True)

     def __init__(self, *args, **kwargs):
         super(UserSerializer, self).__init__(*args, **kwargs)

         self.fields['first_name'].error_messages['required'] = 'Please enter your first name.'
         self.fields['first_name'].error_messages['invalid'] = 'Please enter a valid name.'
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • I changed this to 'blank' instead of 'required' at the fields; some fields use 'required's, some 'blank's. Thanks Chandu, Rahul. – user2307087 Jun 04 '15 at 01:43