Django rest框架字段级的表单验证



我使用ModelViewSet和TemplateHTMLRenderer来使用表单和过程'post'方法。当我尝试呈现一个字段错误时,错误呈现[u'此字段可能不是空白的。']。我如何使它呈现简单的消息"This…"?

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

在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})

我在serializer.py中覆盖了rest框架的默认必需错误消息,但它似乎忽略了自定义的必需错误消息,并显示默认的必需错误消息,如'This field may not be blank..'。

在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.')})

怎么了?

没有出现错误,因为DRF最初正在运行字段验证。如果这些验证失败,则显示默认错误。

根据源代码,默认的错误消息存储在default_error_messages字典中。以下是一些代码片段:

:

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.')
    }

所以,你能做的就是通过重写序列化器的__init__方法来重写default_error_messages值,并提供你自定义的错误消息。

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

相关内容

  • 没有找到相关文章

最新更新