django rest框架字段级别验证的形式

时间:2015-06-03 07:52:40

标签: django validation field django-rest-framework

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

in html,

<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框架的默认必需错误消息,但它似乎忽略了自定义的必需错误消息,并显示了默认所需的错误消息,例如“此字段可能不是空白..”。

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

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

错误未到来,因为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.')
    }

因此,您可以通过覆盖序列化程序的default_error_messages方法覆盖__init__值并提供自定义错误消息。

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